Search code examples
c#jsondynamicdeserialization

Deserializing JSON with dynamic keys


I'm quite new to JSON, and am currently learning about (de)serialization. I'm retrieving a JSON string from a webpage and trying to deserialize it into an object. Problem is, the root json key is static, but the underlying keys are dynamic and I cannot anticipate them to deserialize. Here is a mini example of the string :

{
    "daily": {
        "1337990400000": 443447,
        "1338076800000": 444693,
        "1338163200000": 452282,
        "1338249600000": 462189,
        "1338336000000": 466626
    }
}

For another JSON string in my application, I was using a JavascriptSerializer and anticipating the keys using class structure. What's the best way to go about deserializing this string into an object?


Solution

  • Seriously, no need to go down the dynamic route; use

    var deser = new JavaScriptSerializer()
        .Deserialize<Dictionary<string, Dictionary<string, int>>>(val);
    var justDaily = deser["daily"];
    

    to get a dictionary, and then you can e.g.

    foreach (string key in justDaily.Keys)
        Console.WriteLine(key + ": " + justDaily[key]);
    

    to get the keys present and the corresponding values.