Deserializing JSON in WP7

前端 未结 2 858
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-13 07:23

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 r

2条回答
  •  一生所求
    2021-01-13 08:17

    The solution below uses Json.NET. It deserializes the JSON string first to XML, then uses LINQ to XML to iterate all people nodes and convert them to instances of the Person class.

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

    Don't forget the imports:

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

    And this is how the deserialized JSON looks like as XML document (for the curious people out there):

    
      16:12
      
        x
        x
        x
      
      
        x
        x
        x
      
      
        x
        x
        x
      
      
        blah blah text
      
    
    

提交回复
热议问题