Windows Phone 7

wp7–JSON parsing

Peter Daukintis

I’m writing this mainly as a central place to store this code as I need to use it frequently – hopefully it will help others also.

Supposing I have a web service that I want to call that returns me some JSON data. I want to get that from the service and into a class which I will use as a domain model in my application. The first thing to do is to make sure that we understand the hierarchy that the JSON data represents. So for example,

{ IsSuccess: true }

is an object with a boolean property ‘IsSuccess’ which in this case is true. So we can read the {}’s as enclosing an object.

[{ IsSuccess: true },{ IsSuccess: false }]  

This represents an array of objects; read the []’s as enclosing an array.

Here’s a slightly more complicated example:

// start
         "Nickname":"2007 Ninja ZX6R",
         "Nickname":"Luminous Neptune",

(Note – useful JSON formatter here

I can interpret this as an object with a property ‘FleetsCollection’ which is a list of objects which have further properties. In fact, if you take your JSON string data you can convert it to a c# class using this online tool

For our example, the online tool generates,

public class FleetsCollection
    public int FleetId { get; set; }
    public string Nickname { get; set; }
    public string PictureFileName { get; set; }
    public double AverageMpg { get; set; }
    public double MaxMpg { get; set; }

public class RootObject
    public List<FleetsCollection> FleetsCollection { get; set; }

Then, we can read the data in using the following code:

var dataContractJsonSerializer = new DataContractJsonSerializer(typeof(RootObject));
RootObject readObject = (RootObject)dataContractJsonSerializer.ReadObject(memoryStream);

Tagged , , ,

1 thought on “wp7–JSON parsing

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.