Search code examples
c#asp.netjsonjavascriptserializer

How can I use JavaScriptSerializer in c# to parse Json with unknown number of Keys and Values?


If I had a Json string with unknown number of Keys and values. How can I obtain all values into an array or object in c#?

In the following example I know there is "id" and "index" fields. What if I didn't know the Keys in the field?

In another context, What if the number of keys is large in number so that I Can't declare variables?

[{"id":"449342","index":0},{"id":"449343","index":1}]

I deserialize the above Json like this. What about the two contexts mentioned above?

JavaScriptSerializer js = new JavaScriptSerializer();
        AllLiTags[] Tags = js.Deserialize<AllLiTags[]>(LiOrder);

public class AllLiTags
{
    public string Id { get; set; }
    public string Index { get; set; }
}

Solution

  • Either deserialize into a dictionary, or grab the nuget package Json.NET, (documentation) which is more oriented towards this kind of usage.

    Deserializing into a dictionary would look like:

    var tags = js.Deserialize<Dictionary<string, string>[]>(LiOrder);
    string secondOrderIndex = tags[1]["index"];
    

    You'd lose type information (numbers converted to strings, etc), and I doubt it would deal with nested objects.

    Using Json.NET would look like:

    var tags = JArray.Parse(LiOrder);
    string secondOrderIndex = tags[1]["index"].GetValue<string>();
    int idx = 0;
    foreach (var order in tags) {
        foreach (var prop in order) {
            Console.WriteLine("Order {0}'s {1} property has value {2}",
                              idx,
                              prop.Name,
                              prop.Value.ToString());
        }
        idx++;
    }