2

I'm having some issues getting JsonConvert.DeserializeObject to work with some JSON where the object name is dynamic, which is making it hard to deserize into a C# object. Here's what I would normally do - which works fine for JSON that has a predictable schema:

var dynData = (MyType)JsonConvert.DeserializeObject(jsonString, typeof(MyType));

The incoming JSON looks like this, noting that the object name "2000314370" is dynamic and won't be the same every time. The JSON is provided by a 3rd party so I have no control over it.

{
  "status":"ok",
  "meta":{"count":1},
  "data":{
       "2000314370":[
              {"all": {"f1":972,"f2":0,"f3":0.09}}
                    ]
         }
}

Using http://jsonutils.com/ I generated what it thought was the right class structure, but of course it includes references to the dynamic object:

public class 2000314370
{
    public All all { get; set; }
}

public class Data
{
    public IList<2000314370> 2000314370 { get; set; }
}

Am I able to declare classes and deserialize the dynamic JSON to it, or will I have to use a different approach?

Adrian K
  • 9,880
  • 3
  • 33
  • 59
  • 2
    change data property to a dictionary of string and contained type – Nkosi May 28 '18 at 01:02
  • 2
    Looks like a duplicate of [How can I parse a JSON string that would cause illegal C# identifiers?](https://stackoverflow.com/a/24536564/3744182) or [Create a strongly typed c# object from json object with ID as the name](https://stackoverflow.com/a/34213724/3744182) – dbc May 28 '18 at 01:04
  • Here is a very interesting way to do it: https://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object – Mikaal Anwar May 28 '18 at 01:26

1 Answers1

4

Change data property of the root object to a dictionary of string and contained data type. Which in this case is an array of objects.

public class Meta {
    public int count { get; set; }
}

public class All {
    public int f1 { get; set; }
    public int f2 { get; set; }
    public double f3 { get; set; }
}

public class Data {
    public All all { get; set; }
}

public class MyType {
    public string status { get; set; }
    public Meta meta { get; set; }
    public IDictionary<string, IList<Data>> data { get; set; }
}

so now when deserialized

var dynData = JsonConvert.DeserializeObject<MyType>(jsonString);
All all =  dynData.data["2000314370"][0].all; //  {"f1":972,"f2":0,"f3":0.09}}
Nkosi
  • 235,767
  • 35
  • 427
  • 472