简体   繁体   中英

How to parse Json objects inside array?

[{"conversation":{"id":"04d27d987de7f897580096b099815691cd4a89_ecf47fb8-cd72-4e5d-925c-5a63aa2fb315","wid":"04d27d987de7f897580096b099815691cd4a89","nicknames":{"owner":"Wiz_boltebony","originator":"Username123"},"group_token":"5a4b2b9d-ed39-4029-a76e-347a8c99806b"}},{"conversation":{"id":"05043a6393ec32806194414f2239a8697fa788_ecf47fb8-cd72-4e5d-925c-5a63aa2fb315","wid":"05043a6393ec32806194414f2239a8697fa788","nicknames":{"owner":"Summer_Reflection","originator":"Wiz_boltebony"},"group_token":"0b77eb02-aa57-4811-91fd-5fa61997b6a0"}}]

I want to parse out all of the (group_token":"0b77eb02-aa)...etc values from this json "array".

Here is my code:

dynamic j = JsonConvert.DeserializeObject(contents);
foreach (var c in j[0]["conversation"])
{
    Console.WriteLine(c["group_token"]);
}

Here is an image on how the JSON is laid out: http://gyazo.com/5840a31b71d4cbea626899030debe5d8

My code doesn't work at all! How do I go about extracting these group_token values?

You need to change your code a little bit (iterate through objects, not properties);

dynamic j = JsonConvert.DeserializeObject(contents);
foreach (var c in j)
    Console.WriteLine(c["conversation"]["group_token"]);

Your current code iterates through properties of first conversation object and tries to get group_token child of each property, which is wrong.

You can try below as well. Totally agreed with @Ulugbek Umirov

var _jArr = (JArray)JsonConvert.DeserializeObject(contents);
IEnumerable<string> _groupToken = _jArr.Select(conv => conv["conversation"]["group_token"].ToString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM