Yooooomi
Yooooomi

Reputation: 985

Navigating through dynamic Object (json) in C#

i'm getting a json from a HTTP GET request that looks like after parsing it with "NewtonSoft.Json":

dynamic data = JsonConvert.DeserializeObject(responseString);

Where responseString is :

{"name1":{"id":123456789,"name":"nickname","profileIconId":1114,"summonerLevel":30}}

As you see, the name changes everytime, and i was wondering how do I navigate through this like data.name1.name where name1 changes everytime.

And how do i do if the json looks like :

{"name1":{"id":123456789,"name":"nickname","profileIconId":1114,"summonerLevel":30},"name2":{"id":123456789,"name":"nickname","profileIconId":948,"summonerLevel":30}}

Upvotes: 10

Views: 11557

Answers (1)

David L
David L

Reputation: 33853

You can deserialize to JObject instead of dynamic, which gives you access to handy properties such as First which allow you to walk down the object structure without knowing the property name, as well as iterate over the objects on data with a foreach loop, based on your edit.

Once you reach the desired level, you can then resolve the JObject into a strong type with the ToObject extension method.

Note that you'll need to include the Newtonsoft.Json.Linq namespace.

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

void Main()
{
    var responseString = "{\"name1\":{\"id\":123456789,\"name\":\"nickname\",\"profileIconId\":1114,\"summonerLevel\":30},\"name2\":{\"id\":123456789,\"name\":\"nickname\",\"profileIconId\":948,\"summonerLevel\":30}}";
    JObject data = JsonConvert.DeserializeObject<JObject>(responseString);
    var names = new List<Name>();

    foreach (var x in data) names.Add(x.Value.ToObject<Name>());
    names.Dump();
}

public class Name
{
    public int id { get; set; }
    public string name { get; set; }
    public int profileIconId { get; set; }
    public int summonerLevel { get; set; }
}

If you prefer LINQ, you can always retrieve the values per the Values() method on the JObject and select each member.

var names = data.Values().Select(x => x.ToObject<Name>()).ToList();

This results in the following collection of Name objects.

enter image description here

Upvotes: 10

Related Questions