Pertanyaan Deserializing JSON dalam WP7


Saya memiliki JSON ini yang saya coba baca di Windows Phone. Saya telah bermain dengan DataContractJsonSerializer dan Json.NET tetapi tidak terlalu beruntung, terutama membaca setiap 'entri':

{"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":
    []
  }
}

Yang saya pedulikan adalah entri di bagian orang. Pada dasarnya saya perlu membaca dan mengulang melalui entri (berisi ID, Nama, nilai Umur) dan menambahkannya ke Koleksi atau kelas. (Saya mengisi listbox sesudahnya.)

Setiap pointer dihargai.


5
2017-11-20 13:54


asal


Jawaban:


Saya dapat mendesentralisasi string JSON Anda menggunakan kode berikut. Ini diuji dalam aplikasi konsol NET. 4, dan mudah-mudahan akan bekerja di WP 7 juga.

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

Menggunakan kelas data berikut:

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

6
2017-11-20 15:26



Solusinya di bawah ini menggunakan Json.NET. Ini deserializes string JSON pertama ke XML, kemudian menggunakan LINQ ke XML untuk mengiterasi semua node orang dan mengkonversikannya ke instance dari Person kelas.

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

Jangan lupakan impor:

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

Dan ini adalah bagaimana JSON deserialized tampak seperti dokumen XML (untuk orang-orang penasaran di luar sana):

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

1
2017-11-20 15:27