json.net - loop over dictionary object in c# -
i have dictionary userdata of type string object. make http call data.
internal static dictionary<string, object> userdata = null; **userdata = newtonsoft.json.jsonconvert.deserializeobject<dictionary<string, object>>(httpdata);** structure of userdata this
{ "id": "12345", "class": [ "my-user", "college-student" ], "list": [ { "a": "cse", "b": "database" }, { "a": "it", "b": "computernetwork" } ] } now have iterate on userdata retrieve value of , b. can please me in c#
the easiest way code have:
var arr = (jarray)userdata["list"]; foreach (jobject item in arr) { console.writeline("a: {0}", item["a"]); console.writeline("b: {0}", item["b"]); console.writeline(); } the value in userdata key "list" jarray of jobjects, each containing "a" , "b" property.
however, (better) way create few classes represent json structure:
public class listitem { public string { get; set; } public string b { get; set; } } public class myclass { public string id { get; set; } public list<string> @class { get; set; } public list<listitem> list { get; set; } } and deserialize instance of myclass instead:
var userdata = jsonconvert.deserializeobject<myclass>(json); foreach (listitem item in userdata.list) { console.writeline("a: {0}", item.a); console.writeline("b: {0}", item.b); console.writeline(); }
Comments
Post a Comment