Reputation: 1394
I am new in C# please clarify how to parse this JSON. I need to iterate over inner arrays to extract some data. JSON:
{
"p": [{
"p": [{
"p": "Get in ",
"f": [],
"t": "t"
},
{
"p": "test",
"t": "lb",
"id": "Make"
},
....
for example need access to dictionary "{"p": "Get in ", "f": [], "t": "t"}" Do the following:
Dictionary<string, object> result = JsonConvert.DeserializeObject<Dictionary<string, object>>(bodyString);
List<Dictionary<string, object>> itemsArray = result["p"] as List<Dictionary<string, object>>;
foreach(var itemInfo in itemsArray)
{
}
But itemsArray is null.
Upvotes: 1
Views: 71
Reputation: 49311
If you deserialize as a dictionary of string to object, the objects will be JArray, Jobject or JToken. { var result = JsonConvert.DeserializeObject>(json);
Console.WriteLine((result["p"]).GetType().Name);
}
Will output 'JArray'.
You could work with JArray and so on, or specify the full structure you want:
{
var result = JsonConvert.DeserializeObject<Dictionary<string, List<Dictionary<string,List<Dictionary<string,object>>>>>>(json);
Console.Write((result["p"]).GetType().Name);
var itemsArray = result["p"];
var item = result["p"][0]["p"][0];
foreach(var entry in item)
Console.WriteLine(entry.Key + " = " + entry.Value);
}
Upvotes: 0
Reputation: 4047
If you create a model to fit the data, then you won't have to worry about issues with multiple levels of dictionary deserialization.
void Main()
{
var json = @"{
""p"":[
{
""p"":[
{
""p"":""Get in "",
""f"":[
],
""t"":""t""
},
{
""p"":""test"",
""t"":""lb"",
""id"":""Make""
}
]
}
]
}";
var data = JsonConvert.DeserializeObject<ItemCollection>(json);
}
public class ItemCollection
{
public ItemGroup[] p { get; set; }
}
public class ItemGroup
{
public Item[] p { get; set; }
}
public class Item
{
public string p { get; set; }
public string t { get; set; }
public string id { get; set; }
public string[] f { get; set; }
}
Upvotes: 3