Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Json.NET, how can I parse a list of objects with dynamic names into a List?

Below is an example of the JSON format I'm receiving from an external API:

"object": {
  "property_1": {
    "values": {
      "value": 1,
      "displayValue": "1"
    }
  },
  "property_5": {
    "values": {
      "value": 3,
      "displayValue": "3"
    }
  },
  "property_8": {
    "values": {
      "value": 1,
      "displayValue": "1"
    }
  },
  "property_14": {
    "values": {
      "value": 392,
      "displayValue": "392.0"
    }
  },
  "property_17": {
    "values": {
      "value": 14,
      "displayValue": "14"
    }
  }
}

There are somewhere around 100 different property types that can be sent, but they all follow the same structure. The only distinction is the name of the property ("property_1", "property_5", etc). Rather than attempting to write a class with a long list of properties that are not always used, I think it'd be much more useful to parse this into a list of objects, using the property name in the resulting class like so:

public class Property
{
    public string Name { get; set; }
    public PropertyValues Values { get; set; }
}

public class PropertyValues
{
    public double Value { get; set; }
    public string DisplayValue { get; set; }
}

In this case, the property name ("property_1", "property_5", etc) would be assigned to the Name field of the Property object.

How can this be accomplished using Json.NET?

like image 265
Rico Avatar asked Dec 24 '22 23:12

Rico


1 Answers

var result  = JsonConvert.DeserializeObject<Root>(json);

You model is below


public class Root
{
    public Dictionary<string, ValueWrapper> Object { get; set; }
}
public class ValueWrapper
{
    public PropertyValues Values { get; set; }
}

public class PropertyValues
{
    public int Value { get; set; }
    public string DisplayValue { get; set; }
}

BTW: Json.Net can handle dynamic more easily than proposed by @MatíasFidemraizer...

var val = ((dynamic)JsonConvert.DeserializeObject(jsonstring))
          [email protected]_14.values.value;

var val = ((dynamic)JsonConvert.DeserializeObject(jsonstring))
          .@object["property_14"].values.value;

But this approach would require you to know property_14 will be returned by your server beforehand...

like image 113
L.B Avatar answered Dec 31 '22 14:12

L.B