mahu
mahu

Reputation: 297

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:

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"
}

Upvotes: 0

Views: 537

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039428

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

Upvotes: 3

Rafal
Rafal

Reputation: 12629

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.

Upvotes: 1

Related Questions