简体   繁体   中英

Deserialize JSON Objects to .Net List (C#)

I have a JSON-String (below). I want to deserialize it to a C# Object and get the data as a list. My problem is, that the data is not available in an JSON array. How do I need to prepare my solution that I can get data in this structure:

  • Sensors
    • Sensor 1
    • Sensor 2
    • Sensor 3

For Sensor 1 - n I just need the GUIDs in a list. The data behind is not relevant.

In the Code I replaced all GUIDs with "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"
}

You could use the Newtonsoft.Json package like so:

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);
}

This will print all the GUID properties of the object node.

And if you wanted to get the extra objects you could define a model:

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

    public Guid Owner { get; set; }

    public string Description { get; set; }

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

    ...
}

and then you could get the sensor like this:

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

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

Structure you provided looks like a dictionary so it should deserialize to:

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

From this you can extract list of keys ( data.Object.Keys ) that will contain your list of Guids.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM