{
"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; }
}
我试图反序列化从一个以太网设备接收的JSON字符串。我收到的JSON字符串在上面。C#JSON反序列化对象内的对象列表
我已经制定了如何反序列化才能到DeviceStatus.totalDevices,.startIndex,.utcTimestamp等
但是当我做了Console.WriteLine(string.Format("Device 1 ID = {0}",jsonRootObj.deviceStatus.device[0].identifier));
我得到一个异常
未将对象引用设置为一个对象的实例
我确定我缺少一些非常简单的东西,但这是我第一次使用C#项目,所以无法解决这个问题。
我已经做了很多搜索,在这里让我到这一点,但不能进一步。
感谢
可能重复[什么是NullReferenceException,以及如何解决它?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-doi-i-fix -it) –
在你的json中,属性'list'必须被命名为'device'或者使用'[JsonProperty(“list”)]来重命名'device'属性,并且你的json是无效的。你最后错过了一个'}' –