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?

3

1 Answer 1

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}}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.