我有这样的JSON,我想读在Windows Phone上。我一直在玩 DataContractJsonSerializer
和Json.NET但实际上并没有多少运气,尤其是阅读每一个'入门':
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":
[]
}
}
我所关心的是,在人们部分中的条目。基本上,我需要阅读并遍历(包括ID,姓名,年龄值)的条目,并将其添加到集合或类。 (我填充列表框之后。)
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.)
任何指针AP preciated。
Any pointers appreciated.
我可以用下面的code反序列化的JSON字符串。这是在.NET 4控制台应用程序进行测试,并希望将WP 7正常工作。
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; }
}