在WP7中反序列化JSON

时间:2011-11-20 13:54:15

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

我有这个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,Name,Age值)并将它们添加到Collection或类中。 (之后我填充了一个列表框。)

任何指示赞赏。

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:1)

下面的解决方案使用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>