Deserializing JSON in WP7

前端 未结 2 882
佛祖请我去吃肉
佛祖请我去吃肉 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:09

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

    Using the following data classes:

    [DataContract]
    public class PersonCollection
    {
        [DataMember(Name = "people")]
        public IEnumerable 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; }
    }
    

提交回复
热议问题