【问题标题】:Deserializing JSON in WP7在 WP7 中反序列化 JSON
【发布时间】:2011-11-20 13:54:15
【问题描述】:

我有这个 JSON,我想在 Windows Phone 上读取它。我一直在玩DataContractJsonSerializer 和 Json.NET 但运气不佳,尤其是阅读每个“条目”:

{"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、名称、年龄值)并将它们添加到集合或类中。 (之后我会填充一个列表框。)

任何指针表示赞赏。

【问题讨论】:

  • 你的例子不是有效的json,请发布真实的东西:-)
  • 好的,我刚刚更改了文本并将其格式化为单独的行。为什么说它无效?

标签: c# .net json windows-phone-7 json.net


【解决方案1】:

我能够使用以下代码反序列化您的 JSON 字符串。这在 .NET 4 控制台应用程序中进行了测试,希望也能在 WP 7 中运行。

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

【讨论】:

  • 这太完美了,谢谢你,我很好地修改了它以填充我的收藏。对我来说棘手的一点是如何枚举它,但 PersonCollection 似乎很好地解决了这个问题。
【解决方案2】:

以下解决方案使用 Json.NET。它首先将 JSON 字符串反序列化为 XML,然后使用 LINQ to XML 迭代所有人员节点并将它们转换为 Person 类的实例。

private class Person
{
    public string ID { get; set; }
    public string Name { get; set; }
    public string Age { get; set; }
}

// deserializes your JSON and creates a list of Person objects from it
private void button1_Click(object sender, RoutedEventArgs e)
{
    // your JSON
    string json =
        "{\"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\":" +
        "[]" +
        "}" +
        "}";

    // deserialize from JSON to XML
    XDocument doc = JsonConvert.DeserializeXNode(json, "root");

    // iterate all people nodes and create Person objects
    IEnumerable<Person> people = from person in doc.Element("root").Elements("people")
                                 select new Person()
                                 {
                                     ID = person.Element("ID").Value,
                                     Name = person.Element("Name").Value,
                                     Age = person.Element("Age").Value
                                 };

    // this is just demonstrating that it worked
    foreach (Person person in people)
        Debug.WriteLine(person.Name);
}

不要忘记导入:

using Newtonsoft.Json;
using System.Xml.Linq;
using System.Diagnostics;

这就是反序列化的 JSON 作为 XML 文档的样子(对于好奇的人来说):

<root>
  <lastUpdated>16:12</lastUpdated>
  <people>
    <ID>x</ID>
    <Name>x</Name>
    <Age>x</Age>
  </people>
  <people>
    <ID>x</ID>
    <Name>x</Name>
    <Age>x</Age>
  </people>
  <people>
    <ID>x</ID>
    <Name>x</Name>
    <Age>x</Age>
  </people>
  <serviceDisruptions>
    <infoMessages>blah blah text</infoMessages>
  </serviceDisruptions>
</root>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-27
    • 2013-02-18
    • 2012-01-29
    • 2011-09-17
    • 2023-04-10
    相关资源
    最近更新 更多