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.
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With