Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing JSON in WP7

I have this JSON which I am trying to read on Windows Phone. I've been playing with DataContractJsonSerializer and Json.NET but had not much luck, especially reading each 'entry':

{"lastUpdated":"16:12","filterOut":[],"people":
[{"ID":"x","Name":"x","Age":"x"},{"ID":"x","Name":"x","Age":"x"},{"ID":"x","Name":"x","Age":"x"}],
 "serviceDisruptions":
  {
    "infoMessages":
    ["blah blah text"],
    "importantMessages":
    [],
    "criticalMessages":
    []
  }
}

All I care about is the entries in the people section. Basically I need to read and iterate through the entries (containing the ID, Name, Age values) and add them to a Collection or class. (I am populating a listbox afterwards.)

Any pointers appreciated.

like image 602
Dan Sewell Avatar asked Nov 20 '11 13:11

Dan Sewell


1 Answers

I was able to deserialize your JSON string using the following code. This was tested in a .NET 4 console application, and hopefully will work in WP 7 as well.

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(PersonCollection));

string json =  "{\"lastUpdated\":\"16:12\",\"filterOut\":[],\"people\": [{\"ID\":\"a\",\"Name\":\"b\",\"Age\":\"c\"},{\"ID\":\"d\",\"Name\":\"e\",\"Age\":\"f\"},{\"ID\":\"x\",\"Name\":\"y\",\"Age\":\"z\"}], \"serviceDisruptions\": { \"infoMessages\": [\"blah blah text\"], \"importantMessages\": [], \"criticalMessages\": [] } }";

using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
    var people = (PersonCollection)serializer.ReadObject(stream);

    foreach(var person in people.People)
    {
        Console.WriteLine("ID: {0}, Name: {1}, Age: {2}", person.ID, person.Name, person.Age);
    }
}   

Using the following data classes:

[DataContract]
public class PersonCollection
{
    [DataMember(Name = "people")]
    public IEnumerable<Person> People { get; set; }
}

[DataContract]
public class Person
{
    [DataMember]
    public string ID { get; set; }

    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public string Age { get; set; }
}
like image 150
Jeff Ogata Avatar answered Sep 23 '22 09:09

Jeff Ogata