c# - Deserializing JSON into an object -


i have json:

{     "foo" : [          { "bar" : "baz" },         { "bar" : "qux" }     ] } 

and want deserialize collection. have defined class:

public class foo {     public string bar { get; set; } } 

however, following code not work:

 jsonconvert.deserializeobject<list<foo>>(jsonstring); 

how can deserialize json?

that json not foo json array. code jsonconvert.deserializeobject<t>(jsonstring) parse json string from root on up, , type t must match json structure exactly. parser not going guess which json member supposed represent list<foo> you're looking for.

you need root object, represents json root element.

you can let classes generated sample json. this, copy json , click edit -> paste special -> paste json classes in visual studio.

alternatively, same on http://json2csharp.com, generates more or less same classes.

you'll see collection 1 element deeper expected:

public class foo {     public string bar { get; set; } }  public class rootobject {     public list<foo> foo { get; set; } } 

now can deserialize json root (and sure rename rootobject useful):

var rootobject = jsonconvert.deserializeobject<rootobject>(jsonstring); 

and access collection:

foreach (var foo in rootobject.foo) {     // foo `foo`  } 

you can rename properties follow casing convention , apply jsonproperty attribute them:

public class foo {     [jsonproperty("bar")]     public string bar { get; set; } } 

also make sure json contains enough sample data. class parser have guess appropriate c# type based on contents found in json.


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -