将JSON对象反序列化为.Net列表(C#)

时间:2017-01-13 10:07:49

标签: c# json list serialization

我有一个JSON-String(下面)。我想将它反序列化为C#对象并将数据作为列表获取。我的问题是,数据在JSON数组中不可用。我如何准备我的解决方案,我可以在此结构中获取数据:

  • 传感器
    • 传感器1
    • 传感器2
    • 传感器3

对于传感器1 - n我只需要列表中的GUID。背后的数据无关紧要。

在代码中,我用" GUID"

替换了所有GUID
{
  "object": {
    "GUID": {
      "type": "sensor",
      "owner": "GUID",
      "time": 1482499665,
      "description": "Temperatursensor 1",
      "sdevice": "00003639",
      "model": "SOLUCON Industry Temperature",
      "tag": [
        "GUID",
        "GUID"
      ]
    },
    "GUID": {
      "type": "sensor",
      "owner": "GUID",
      "time": 1482499758,
      "description": "Wassersensor 1",
      "sdevice": "000056d9",
      "model": "SOLUCON Industry Water",
      "tag": [
        "GUID",
        "GUID"
      ]
    },
    "GUID": {
      "type": "sensor",
      "owner": "GUID",
      "time": 1482499797,
      "description": "Rauchmelder 1",
      "sdevice": "00008519",
      "model": "TG551A",
      "tag": [
        "GUID",
        "GUID"
      ]
    },
    "GUID": {
      "type": "sensor",
      "owner": "GUID",
      "time": 1483888365,
      "description": "SOLUCON Industry Multi 2",
      "sdevice": "0000d409",
      "model": "SOLUCON Industry Multi",
      "tag": [
        "GUID",
        "GUID"
      ]
    }
  },
  "status": "ok"
}

2 个答案:

答案 0 :(得分:3)

您可以像这样使用Newtonsoft.Json包:

var jsonString = ...
var result = JsonConvert.DeserializeObject<IDictionary<string, object>>(jsonString);
var obj = (JObject)result["object"];
foreach (var prop in obj.Properties())
{
    Console.WriteLine(prop.Name);
}

这将打印object节点的所有GUID属性。

如果你想获得额外的对象,你可以定义一个模型:

public class Item
{
    public string Type { get; set; }

    public Guid Owner { get; set; }

    public string Description { get; set; }

    public IList<string> Tag { get; set; }

    ...
}

然后你就可以得到这样的传感器:

foreach (var prop in obj.Properties())
{
    Console.WriteLine(prop.Name);

    Sensor sensor = prop.Value.ToObject<Sensor>();
}

答案 1 :(得分:1)

您提供的结构看起来像字典,因此它应反序列化为:

class Data
{
    public Dictionary<Guid, Sensor> Object {get;set;}
}

通过此,您可以提取包含Guid列表的键列表(data.Object.Keys)。