Merlin Merlin - 1 year ago 236
JSON Question

How do I correctly parse a JSON string using Newtonsoft.json to an object in C#?

I'm creating a little system to let me see who is in my chat on Twitch using their JSON API. However, while I successfully got the information, I can't figure out how to parse it correctly.

This is the string that is being produced:

"_links": {},
"chatter_count": 1,
"chatters": {
"moderators": [
"staff": [],
"admins": [],
"global_mods": [],
"viewers": []

This is the object I created to deserialize it to, but I have no idea for sure if it's exactly correct:

public class users
public string[] links;
public int chatter_count;
public string[] moderators;
public string[] staff;
public string[] admins;
public string[] global_mods;
public string[] viewers;

I'm using Newtonsoft.JSON to parse it - which would be the correct way to push the string to the "users" object?

Answer Source

No, the C# class you have doesn't really correlate correctly to the JSON:

  1. Your links member doesn't match the name _links in JSON.
  2. _links is defined as an array, but should be an object - it's {} in JSON, not [].
  3. Likewise chatters, which should be a custom class as well.

Starting with Visual Studio 2013 Update 2, you can generate a C# class from a JSON sample. This is what it generated for your JSON:

public class Rootobject
    public _Links _links { get; set; }
    public int chatter_count { get; set; }
    public Chatters chatters { get; set; }

public class _Links

public class Chatters
    public string[] moderators { get; set; }
    public object[] staff { get; set; }
    public object[] admins { get; set; }
    public object[] global_mods { get; set; }
    public object[] viewers { get; set; }

As you can see, it maps moderators properly to a string[] but gets a bit confused and uses object[] for the rest, because the snippet contains to data for it to base the type on.

If you can get a JSON sample with more data - ideally, with every field being present and having representative data - you'll get the best mapping.

Also, you should change Rootobject to your own class name, of course. User or TwitchUser should do it.

Once you have a class that corresponds correctly to your JSON, using JSON.NET to parse it is very simple:

Rootobject yourData = JsonConvert.DeserializeObject<Rootobject>(inputJsonString);

And you're done.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download