Populate JSON List To C# Object -
i'm trying populate json/xml string c# object. convert xml json , use json.net. example:
json string
{ "persons":[ { "age":30, "name":"david", "hobbies":[ { "name":"tennis", "hours":5 }, { "name":"football", "hours":10 } ] }, { "name":"adam", "age":23, "hobbies":[] } ] }
c# classes
public class hobbies { public string name; public int hours; } class person { public string name; public int age; public list<hobbies> hoobies = new list<hobbies>(); }
i'm trying populate data list of persons:
list<person> persons = new list<person>(); jsonconvert.populateobject(myjsontext, persons);
and i'm getting exception:
cannot populate json object onto type
how can that?
here json
representation of object:
{ "key":"value" }
and here representation of collection/array/list of object
[ { "key":"value" }, { "key2":"value2" } ]
so json
string doesn't representing array or collection of person
class. it's representing object persons
property collection of person
object.
to parse list<person>
, remove outermost {
}
, try.
your json should this
[ { "age": 30, "name": "david", "hobbies": [ { "name": "tennis", "hours": 5 }, { "name": "football", "hours": 10 } ] }, { "name": "adam", "age": 23, "hobbies": [] } ]
and deserialize this
var result = jsonconvert.deserializeobject<list<person>>(json);
Comments
Post a Comment