Pete
Pete

Reputation: 3451

Can't figure out how to deserialize this JSON into C#

I've tried several deserializers but can't figure out how to get an array of entries rather than a class for each entry. Below is the json2csharp input and output.

[
  {
    "subdeviceGuid": "000781000030534e",
    "componentId": "all",
    "entries": {
      "1619701200000": {
        "min": 0.437,
        "max": 2.014,
        "mean": 0.751
      },
      "1619704800000": {
        "min": 0.526,
        "max": 2.089,
        "mean": 0.893
      },
      "1619708400000": {
        "min": -1.456,
        "max": -0.989,
        "mean": -1.328
      }
    }
  }
]

and the c# classes created by https://json2csharp.com/

// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); 
    public class _1619701200000
    {
        public double min { get; set; }
        public double max { get; set; }
        public double mean { get; set; }
    }

    public class _1619704800000
    {
        public double min { get; set; }
        public double max { get; set; }
        public double mean { get; set; }
    }

    public class _1619708400000
    {
        public double min { get; set; }
        public double max { get; set; }
        public double mean { get; set; }
    }

    public class Entries
    {
        public _1619701200000 _1619701200000 { get; set; }
        public _1619704800000 _1619704800000 { get; set; }
        public _1619708400000 _1619708400000 { get; set; }
    }

    public class Root
    {
        public string subdeviceGuid { get; set; }
        public string componentId { get; set; }
        public Entries entries { get; set; }
    }

Upvotes: 0

Views: 78

Answers (1)

Hans Kilian
Hans Kilian

Reputation: 25587

Auto-generated classes usually have issues with JSON structures that are best represented as dictionaries. Try these classes instead

public class Entry
{
    public double min { get; set; }
    public double max { get; set; }
    public double mean { get; set; }
}

public class Root
{
    public string subdeviceGuid { get; set; }
    public string componentId { get; set; }
    public Dictionary<string, Entry> entries { get; set; }
}

Also, your JSON starts with '[' indicating that it's not a single object, but an array. So when you deserialize it, you should deserialize into an array of Root rather than a single instance, like this

Root[] myDeserializedClass = JsonConvert.DeserializeObject<Root[]>(myJsonResponse);

Upvotes: 2

Related Questions