在 WP7 中反序列化 JSON [英] Deserializing JSON in WP7

查看:23
本文介绍了在 WP7 中反序列化 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 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.)

感谢任何指点.

推荐答案

我能够使用以下代码反序列化您的 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);
    }
}   

使用以下数据类:

[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; }
}

这篇关于在 WP7 中反序列化 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆