Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 860
Jason Higgins Avatar asked Nov 22 '12 17:11

Jason Higgins


People also ask

How do I deserialize JSON to an object?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

What is the difference between serialize and deserialize JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object). If you serialize this result it will generate a text with the structure and the record returned.


2 Answers

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.

like image 112
Rawling Avatar answered Oct 15 '22 15:10

Rawling


You can use dynamic in .NET 4 or later. For example with JSON.NET I can do:

dynamic obj = JsonConvert.Deserialize<dynamic>("{x: 'hello'}");

You can then do:

var str = obj.x;

However, unsure how it will handle numeric keys. You can of course just use JObject directly itself, for example:

var obj = JObject.Parse("{'123456': 'help'}");
var str = obj["123456"];
like image 43
Lloyd Avatar answered Oct 15 '22 13:10

Lloyd