C# JSON Deserializing a List of objects within an Object -
{ "devicestatus": { "totaldevices": 3, "startindex": 0, "utctimestamp": 1502782784, "list": [ { "identifier": "000d6f000a9e6e3d:0", "rxtime": 0 }, { "identifier": "000d6f000be977f0:0", "rxtime": 1502782323, "lowbattery": "false", "level": "0", "batterylevel": "84" }, { "identifier": "000d6f000be95e24:0", "rxtime": 1502782754, "lowbattery": "false", "level": "0", "batterylevel": "86" } ] } } public class qube { private const string _json = "{\"devicestatus\":{\"totaldevices\":3,\"startindex\":0,\"utctimestamp\":1502782784,\"list\":[{\"identifier\":\"000d6f000a9e6e3d:0\",\"rxtime\":0},{\"identifier\":\"000d6f000be977f0:0\",\"rxtime\":1502782323,\"lowbattery\":\"false\",\"level\":\"0\",\"batterylevel\":\"84\"},{\"identifier\":\"000d6f000be95e24:0\",\"rxtime\":1502782754,\"lowbattery\":\"false\",\"level\":\"0\",\"batterylevel\":\"86\"}]}}"; public void getstatus() { var jsonrootobj = jsonconvert.deserializeobject<rootobject>(_json); console.writeline(string.format("total devices = {0}, start index = {1}, timestamp = {2}",jsonrootobj.devicestatus.totaldevices,jsonrootobj.devicestatus.startindex,jsonrootobj.devicestatus.utctimestamp)); console.writeline(string.format("device 1 id = {0}",jsonrootobj.devicestatus.device[0].identifier)); console.readline(); } } public class device { public string identifier { get; set; } public int rxtime { get; set; } public string lowbattery { get; set; } public string level { get; set; } public string batterylevel { get; set; } } public class devicestatus { public int totaldevices { get; set; } public int startindex { get; set; } public int utctimestamp { get; set; } public list<device> device { get; set; } } public class rootobject { public devicestatus devicestatus { get; set; } } im trying deserialize json string receive ethernet device. json string receive above.
i have worked out how deserialize devicestatus.totaldevices, .startindex, .utctimestamp etc.
but when console.writeline(string.format("device 1 id = {0}",jsonrootobj.devicestatus.device[0].identifier)); exception
object reference not set instance of object
im sure im missing simple first ever c# project cant work out.
i've done quite alot of searching on here me point cant further.
thanks
in json, property list must named device or rename property device using [jsonproperty("list")]:
public class devicestatus { public int totaldevices { get; set; } public int startindex { get; set; } public int utctimestamp { get; set; } [jsonproperty("list")] public list<device> device { get; set; } } otherwise json.net doesn't know property list belongs , value null - here nullreferenceexception mentioned
Comments
Post a Comment