Deserialise JSON with Newtonsoft Json.NET in C# -
i want parse piece of json newtonsoft json.net
json:
[{ "type": "switchstatus", "data" :[ { "id" : "1", "value" : "2.5" }, { "id" : "2", "value" : "4.2" } ], "datetime": "2014-12-01", "customerid": "50" }]
classes:
public class account { [jsonproperty("type")] public string type { get; set; } public list<data> data { get; set; } [jsonproperty("datetime")] public string datetime { get; set; } [jsonproperty("customerid")] public string customerid { get; set; } }//account public class data { [jsonproperty("id")] public string id { get; set; } [jsonproperty("value")] public string value { get; set; } }
parsing:
account account = jsonconvert.deserializeobject<account>(message);
error :
cannot deserialize current json array (e.g. [1,2,3]) type 'jsonparser.account' because type requires json object (e.g. {"name":"value"}) deserialize correctly.
to fix error either change json json object (e.g. {"name":"value"}) or change deserialized type array or type implements collection interface (e.g. icollection, ilist) list can deserialized json array. jsonarrayattribute can added type force deserialize json array.
path '', line 1, position 1.
your problem json doesn't match declared class. specifically, data
property isn't list<string>
, complex object.
your class should this:
public class data { [jsonproperty("id")] public int id { get; set; } [jsonproperty("value")] public double value { get; set; } } public class account { [jsonproperty("type")] public string type { get; set; } public list<data> data { get; set; } [jsonproperty("datetime")] public string datetime { get; set; } [jsonproperty("customerid")] public int customerid { get; set; } }
edit:
as you've edited json, it's clear need list<account>
, , not single one. when deserialize, you'll need:
list<account> accounts = jsonconvert.deserializeobject<list<account>>(message);
Comments
Post a Comment