Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Windows Phone中的Json解析

From Wiki
Jump to: navigation, search
WP Metro Icon File.png
SignpostIcon WP7 70px.png
Article Metadata

代码示例
兼容于
文章
Xinx Gong 在 24 Oct 2012 创建
最后由 hamishwillee 在 28 Jun 2013 编辑

介绍

  1. 在.net中解析Json字符串,需要用到System.Runtime.Serialization.Json,在Windows Phone7的SDK中,它包含在System.Servicemodel.Web里,所以第一步,需要添加System.Servicemodel.Web的引用。
  2. 添加如下的类,用于序列化和反序列化Json字符串。
        public class JsonParser
    {
    //序列化
    public static string Serialize(object objectToSerialize)
    {
    using (MemoryStream ms = new MemoryStream())
    {
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(objectToSerialize.GetType());
    serializer.WriteObject(ms, objectToSerialize);
    ms.Position = 0;
     
    using (StreamReader reader = new StreamReader(ms))
    {
    return reader.ReadToEnd();
    }
    }
    }
     
    //反序列化
    public static T Deserialize<T>(string jsonString)
    {
    using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
    {
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
    return (T)serializer.ReadObject(ms);
    }
    }
    }
  3. 这样我们就可以将一个Json字符串解析成对应的类,或者一个类序列化成Json字符串。下面再来讲讲如何来做这些事。
  4. 假定我们要解析的Json字符串如下:
        {"country":"Shu","leader":"Liu Bei","generals":[{"name":"Guan Yu","age":25},{"name":"Zhang Fei","age":24}]}
  5. 我们需要先定义两个类,General和Country,属性名对应的是Json字符串中的每一项的名字。如下所示:
        public class General
    {
    public string name { get; set; }
    public int age { get; set; }
    }
     
    public class Country
    {
    public string country { get; set; }
    public string leader { get; set; }
    public General[] generals { get; set; }
    }
  6. 最后调用反序列化的方法就可以完成对指定的Json字符串的解析了。
     Country country = JsonParser.Deserialize<Country>(str);
  7. 如果需要把一个类序列化为Json字符串,只需调用序列化的方法就可以了。
     string countryStr = JsonParser.Serialize(country);

源代码下载

File:JsonParserSample.zip

This page was last modified on 28 June 2013, at 06:36.
277 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×