PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 26, 2022

[FIXED] How do I take a JSON string and select a random entry and get the variables from that entry

 July 26, 2022     c#, json, parsing     No comments   

Issue

I have the following json..

{
    "Followers": [{
        "ID": 0,
        "Username": "nutty",
        "Game": "Just Chatting",
        "Viewers": 200,
        "Image": "https://static-cdn.jtvnw.net/previews-ttv/live_user_nutty-1920x1080.jpg"
    }, {
        "ID": 1,
        "Username": "CloneKorp",
        "Game": "Software and Game Development",
        "Viewers": 31,
        "Image": "https://static-cdn.jtvnw.net/previews-ttv/live_user_clonekorp-1920x1080.jpg"
    }, {
        "ID": 2,
        "Username": "kingswarrior9953",
        "Game": "Art",
        "Viewers": 1,
        "Image": "https://static-cdn.jtvnw.net/previews-ttv/live_user_kingswarrior9953-1920x1080.jpg"
    }]
}

I'd like to do something like..

JObject data = JObject.Parse(json);
int SelectedViewers = data["Followers"][1]["Viewers"];

Where it would grab the second entry (the ID of 1 entry) and set the variable of "Viewers" to 31. The number would be a random number based on the count of all the entries, but I'm not to that point yet.

However, this doesn't seem to work. Any ideas on what is broken here?


Solution

You are missing casting here:

int SelectedViewers = Int32.Parse((string)data["Followers"][1]["Viewers"]);

The above should work.



Answered By - Niraj Bihani
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing