C# – Deserialize JSON Stream with JSON.net

cjsonjson.netwindows-phone-7

I recently switched from using SOAP to JSON. I now have a problem with the performance because it takes about 26 seconds to deserialize the JSON stream on my WP7 device.

Therefore I thought about using Json.net instead of DataContractJsonSerializer.

However, I was not able to find much information about this.

I use a webclient and then OpenReadAsync, so I have a Stream as e.Result.

How can I turn that stream into an object using Json.net?

Should I maybe use DownloadStringAsync instead?

This is the Code that currently works:

//string URL = ""; //Actual URL to JSON is here

WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri(URL, UriKind.Absolute));

And the event handler:

void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
     DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(JSONObject), null);
     JSONObject data = serializer.ReadObject(e.Result) as JSONObject;
}

JSONObject is the response object of the service's SOAP endpoint, but both endpoints return the same data.

This works fine and I can go on and parse data just like I parsed the SOAP response, but I would like it do deserialize faster.

Best Answer

In order to deserialize you'll need the whole JSON. It may be better to use DownloadStringAsync and once you've received the entire JSON string, you can deserialize it.

Then in your DownloadStringCompleted you can pass in the class you want to deserialize it to. For example, if you are receiving JSON like:

{ name: "smoak", title: "super awesome" }

Then you need to create a class with those properties:

class SomeClassName 
{
    publc string name { get;set;}
    public string title { get;set; }
}

and pass it to the JsonConvert:

var deserializedObj = JsonConvert.DeserializeObject<SomeClassName>(e.Result);
Console.WriteLine(deserializedObj.name);