C#JSON反序列化对象中的对象列表

时间:2017-08-15 10:06:47

标签: c# json json.net

{
"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字符串在上面。

我已经研究了如何反序列化以获取DeviceStatus.totalDevices,.startIndex,.utcTimestamp等。

但当我做Console.WriteLine(string.Format("Device 1 ID = {0}",jsonRootObj.deviceStatus.device[0].identifier));时 我得到了一个例外

  

对象引用未设置为对象的实例

我确定我错过了一些非常简单的东西,但这是我的第一个C#项目,因此无法解决问题。

我已经在这里做了很多搜索,以便让我达到这一点,但不能再进一步了解。

由于

2 个答案:

答案 0 :(得分:4)

在您的json中,属性list必须命名为device,或使用device重命名属性[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; }
}

否则Json.Net不知道属性list属于哪个,值为null - 这里你得到你提到的NullReferenceException

答案 1 :(得分:0)

正如Matthias Burger所说,“list”的名称不匹配,因此您的device成员将为空(或者甚至为空,在这种情况下,我认为)。