EddyLee EddyLee - 2 months ago 8
C# Question

DeserializeObject with dynamic name [Json.net]

Dearl all
I have a json string with format line

"rain":{"3h":0.46}


In this case , 'rain' have '3h' object but with this name is dynamic so i can't deserialize object it with JsonConvert , so what are define in class with this name ?

Json2Csharp give me this code

public class Rain
{
public double __invalid_name__3h { get; set; }
}

Rob Rob
Answer

Objects in javascript (and thus JSON) are simply dictionaries. Since you don't know the property name (and more importantly, since it begins with a number which is forbidden in C#), you can simply use a dictionary:

public class MyThing 
{
    public Dictionary<string, double> rain { get; set; }
}

However, your JSON is incomplete. It should be:

{"rain":{"3h":0.46}}

Fully working:

void Main()
{
    var json =  @"{""rain"":{""3h"":0.46}}";
    var result = JsonConvert.DeserializeObject<MyThing>(json);
}

public class MyThing
{
    public Dictionary<string, double> rain { get; set; }
}
Comments