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

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -