David
David

Reputation: 1709

Parsing JSON object to multiple dictionaries

I'm writting a piece of should which has to parse a JSON object to multiple dictionaries. I'm familare with parsing the JSON to a simple model object with a JSON helper.

public static class JsonHelper
{
    public static string ToJson<T>(T instance)
    {
        var serializer = new DataContractJsonSerializer(typeof(T));
        using (var tempStream = new MemoryStream())
        {
            serializer.WriteObject(tempStream, instance);
            return Encoding.UTF8.GetString(tempStream.ToArray(), 0, Convert.ToInt32(tempStream.Length));
        }
    }

    public static T FromJson<T>(string json)
    {
        var serializer = new DataContractJsonSerializer(typeof(T));

        using (var tempStream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
        {
            return (T)serializer.ReadObject(tempStream);
        }

    }
}

But I need to parse it to multiple dictionary and not model object (which is going to be at the end but for the moment I just need dictionaries).

Regards.

Upvotes: 0

Views: 1212

Answers (1)

digEmAll
digEmAll

Reputation: 57210

You could use JavaScriptSerializer class (assembly: System.Web.Extensions).

It automatically deserializes JSon strings to object[] (in case of unnamed arrays) or Dictionary<string,object> (in case of named arrays).

e.g.

1)

// txt = [ {A: "foo", B: "bar", C: "foobar"}, {X: "foo", Y: "bar", Z: "foobar"} ]
JavaScriptSerializer ser = new JavaScriptSerializer();
var data = ser.Deserialize<object>(txt);

data will be an object[2], where each sub-object will be a Dictionary<string,object>

2)

// txt = {A: "foo", B: ["bar", 3.4], C: [1, 2, 3]}
JavaScriptSerializer ser = new JavaScriptSerializer();
var data = ser.Deserialize<object>(txt);  

data will be a Dictionary<string,object>, where elements at keys "B" and "C" will be objects arrays (object[])

Upvotes: 2

Related Questions