C# 解析JSON方法总结

Posted mimime

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# 解析JSON方法总结相关的知识,希望对你有一定的参考价值。

http://blog.csdn.net/jjhua/article/details/51438317

主要参考http://blog.csdn.NET/joyhen/article/details/24805899和http://www.cnblogs.com/yanweidie/p/4605212.html

根据自己需求,做些测试、修改、整理。

使用Newtonsoft.Json

一、用JsonConvert序列化和反序列化。

实体类不用特殊处理,正常定义属性即可,控制属性是否被序列化参照高级用法1。

 

[csharp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. public interface IPerson  
  2. {  
  3.     string FirstName  
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     string LastName  
  9.     {  
  10.         get;  
  11.         set;  
  12.     }  
  13.     DateTime BirthDate  
  14.     {  
  15.         get;  
  16.         set;  
  17.     }  
  18. }  
  19. public class Employee : IPerson  
  20. {  
  21.     public string FirstName  
  22.     {  
  23.         get;  
  24.         set;  
  25.     }  
  26.     public string LastName  
  27.     {  
  28.         get;  
  29.         set;  
  30.     }  
  31.     public DateTime BirthDate  
  32.     {  
  33.         get;  
  34.         set;  
  35.     }  
  36.   
  37.     public string Department  
  38.     {  
  39.         get;  
  40.         set;  
  41.     }  
  42.     public string JobTitle  
  43.     {  
  44.         get;  
  45.         set;  
  46.     }  
  47.   
  48.     public string NotSerialize { get; set; }  
  49. }  
  50. public class PersonConverter : Newtonsoft.Json.Converters.CustomCreationConverter<IPerson>  
  51. {  
  52.     //重写abstract class CustomCreationConverter<T>的Create方法  
  53.     public override IPerson Create(Type objectType)  
  54.     {  
  55.         return new Employee();  
  56.     }  
  57. }  
  58. public class Product  
  59. {  
  60.     public string Name { get; set; }  
  61.     public DateTime Expiry { get; set; }  
  62.     public Decimal Price { get; set; }  
  63.     public string[] Sizes { get; set; }  
  64.     public string NotSerialize { get; set; }  
  65. }  

1.序列化代码:

 

[csharp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. #region 序列化 用JsonConvert  
  2. public string TestJsonSerialize()  
  3. {  
  4.     Product product = new Product();  
  5.     product.Name = "Apple";  
  6.     product.Expiry = DateTime.Now;//.AddDays(3).ToString("yyyy-MM-dd hh:mm:ss");  
  7.     product.Price = 3.99M;  
  8.   
  9.     //string json = Newtonsoft.Json.JsonConvert.SerializeObject(product); //没有缩进输出  
  10.     string json = Newtonsoft.Json.JsonConvert.SerializeObject(product, Newtonsoft.Json.Formatting.Indented);//有缩进输出  
  11.     //string json = Newtonsoft.Json.JsonConvert.SerializeObject(  
  12.     //    product,  
  13.     //    Newtonsoft.Json.Formatting.Indented,  
  14.     //    new Newtonsoft.Json.JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore }//参照高级用法中有关JsonSerializerSettings用法  
  15.     //);  
  16.     return json;  
  17. }  
  18. public string TestListJsonSerialize()  
  19. {  
  20.     Product product = new Product();  
  21.     product.Name = "Apple";  
  22.     product.Expiry = DateTime.Now;//.AddDays(3).ToString("yyyy-MM-dd hh:mm:ss");  
  23.     product.Price = 3.99M;  
  24.     product.Sizes = new string[] { "Small", "Medium", "Large" };  
  25.   
  26.     List<Product> plist = new List<Product>();  
  27.     plist.Add(product);  
  28.     plist.Add(product);  
  29.     string json = Newtonsoft.Json.JsonConvert.SerializeObject(plist, Newtonsoft.Json.Formatting.Indented);  
  30.     return json;  
  31. }  
  32. #endregion  

2.反序列化代码:

 

 

[csharp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. #region 反序列化 用JsonConvert  
  2. public string TestJsonDeserialize()  
  3. {  
  4.     string strjson = "{\\"Name\\":\\"Apple\\",\\"Expiry\\":\\"2014-05-03 10:20:59\\",\\"Price\\":3.99,\\"Sizes\\":[\\"Small\\",\\"Medium\\",\\"Large\\"]}";  
  5.     Product p = Newtonsoft.Json.JsonConvert.DeserializeObject<Product>(strjson);  
  6.   
  7.     string template = @"  
  8.                             Name:{0}  
  9.                             Expiry:{1}  
  10.                             Price:{2}  
  11.                             Sizes:{3}  
  12.                         ";  
  13.   
  14.     return string.Format(template, p.Name, p.Expiry, p.Price.ToString(), string.Join(",", p.Sizes));  
  15. }  
  16. public string TestListJsonDeserialize()  
  17. {  
  18.     string strjson = "{\\"Name\\":\\"Apple\\",\\"Expiry\\":\\"2014-05-03 10:20:59\\",\\"Price\\":3.99,\\"Sizes\\":[\\"Small\\",\\"Medium\\",\\"Large\\"]}";  
  19.     List<Product> plist = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Product>>(string.Format("[{0},{1}]", strjson, strjson));  
  20.   
  21.     string template = @"  
  22.                             Name:{0}  
  23.                             Expiry:{1}  
  24.                             Price:{2}  
  25.                             Sizes:{3}  
  26.                         ";  
  27.   
  28.     System.Text.StringBuilder strb = new System.Text.StringBuilder();  
  29.     plist.ForEach(x =>  
  30.         strb.AppendLine(  
  31.             string.Format(template, x.Name, x.Expiry, x.Price.ToString(), string.Join(",", x.Sizes))  
  32.         )  
  33.     );  
  34.     return strb.ToString();  
  35. }  
  36. #endregion  

3.自定义序列化,使用实体类中定义的PersonConverter,每反序列化一次实体时会调用一次PersonConverter,还没想清楚如何用。

 

 

[csharp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. #region 自定义反序列化  
  2. public string TestListCustomDeserialize()  
  3. {  
  4.     string strJson = "[ { \\"FirstName\\": \\"Maurice\\", \\"LastName\\": \\"Moss\\", \\"BirthDate\\": \\"1981-03-08T00:00Z\\", \\"Department\\": \\"IT\\", \\"JobTitle\\": \\"Support\\" }, { \\"FirstName\\": \\"Jen\\", \\"LastName\\": \\"Barber\\", \\"BirthDate\\": \\"1985-12-10T00:00Z\\", \\"Department\\": \\"IT\\", \\"JobTitle\\": \\"Manager\\" } ] ";  
  5.     List<IPerson> people = Newtonsoft.Json.JsonConvert.DeserializeObject<List<IPerson>>(strJson, new PersonConverter());  
  6.     IPerson person = people[0];  
  7.   
  8.     string template = @"  
  9.                             当前List<IPerson>[x]对象类型:{0}  
  10.                             FirstName:{1}  
  11.                             LastName:{2}  
  12.                             BirthDate:{3}  
  13.                             Department:{4}  
  14.                             JobTitle:{5}  
  15.                         ";  
  16.   
  17.     System.Text.StringBuilder strb = new System.Text.StringBuilder();  
  18.     people.ForEach(x =>  
  19.         strb.AppendLine(  
  20.             string.Format(  
  21.                 template,  
  22.                 person.GetType().ToString(),  
  23.                 x.FirstName,  
  24.                 x.LastName,  
  25.                 x.BirthDate.ToString(),  
  26.                 ((Employee)x).Department,  
  27.                 ((Employee)x).JobTitle  
  28.             )  
  29.         )  
  30.     );  
  31.     return strb.ToString();  
  32. }  
  33. #endregion  

4、获取Json字符串中部分内容

 

[csharp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. #region Serializing Partial JSON Fragment Example  
  2.  public class SearchResult  
  3.  {  
  4.      public string Title { get; set; }  
  5.      public string Content { get; set; }  
  6.      public string Url { get; set; }  
  7.  }  
  8.   
  9.  public string SerializingJsonFragment()  
  10.  {  
  11.      #region  
  12.      string googleSearchText = @"{  
  13.          \'responseData\': {  
  14.              \'results\': [{  
  15.                  \'GsearchResultClass\': \'GwebSearch\',  
  16.                  \'unescapedUrl\': \'http://en.wikipedia.org/wiki/Paris_Hilton\',  
  17.                  \'url\': \'http://en.wikipedia.org/wiki/Paris_Hilton\',  
  18.                  \'visibleUrl\': \'en.wikipedia.org\',  
  19.                  \'cacheUrl\': \'http://www.google.com/search?q=cache:TwrPfhd22hYJ:en.wikipedia.org\',  
  20.                  \'title\': \'<b>Paris Hilton</b> - Wikipedia, the free encyclopedia\',  
  21.                  \'titleNoFormatting\': \'Paris Hilton - Wikipedia, the free encyclopedia\',  
  22.                  \'content\': \'[1] In 2006, she released her debut album...\'  
  23.              },  
  24.              {  
  25.                  \'GsearchResultClass\': \'GwebSearch\',  
  26.                  \'unescapedUrl\': \'http://www.imdb.com/name/nm0385296/\',  
  27.                  \'url\': \'http://www.imdb.com/name/nm0385296/\',  
  28.                  \'visibleUrl\': \'www.imdb.com\',  
  29.                  \'cacheUrl\': \'http://www.google.com/search?q=cache:1i34KkqnsooJ:www.imdb.com\',  
  30.                  \'title\': \'<b>Paris Hilton</b>\',  
  31.                  \'titleNoFormatting\': \'Paris Hilton\',  
  32.                  \'content\': \'Self: Zoolander. Socialite <b>Paris Hilton</b>...\'  
  33.              }],  
  34.              \'cursor\': {  
  35.                  \'pages\': [{  
  36.                      \'start\': \'0\',  
  37.                      \'label\': 1  
  38.                  },  
  39.                  {  
  40.                      \'start\': \'4\',  
  41.                      \'label\': 2  
  42.                  },  
  43.                  {  
  44.                      \'start\': \'8\',  
  45.                      \'label\': 3  
  46.                  },  
  47.                  {  
  48.                      \'start\': \'12\',  
  49.                      \'label\': 4  
  50.                  }],  
  51.                  \'estimatedResultCount\': \'59600000\',  
  52.                  \'currentPageIndex\': 0,  
  53.                  \'moreResultsUrl\': \'http://www.google.com/search?oe=utf8&ie=utf8...\'  
  54.              }  
  55.          },  
  56.          \'responseDetails\': null,  
  57.          \'responseStatus\': 200  
  58.      }";  
  59.      #endregion  
  60.   
  61.      Newtonsoft.Json.Linq.JObject googleSearch = Newtonsoft.Json.Linq.JObject.Parse(googleSearchText);  
  62.      // get JSON result objects into a list  
  63.      List<Newtonsoft.Json.Linq.JToken> listJToken = googleSearch["responseData"]["results"].Children().ToList();  
  64.      System.Text.StringBuilder strb = new System.Text.StringBuilder();  
  65.      string template = @"  
  66.                              Title:{0}  
  67.                              Content: {1}  
  68.                              Url:{2}  
  69.                          ";  
  70.      listJToken.ForEach(x =>  
  71.      {  
  72.          // serialize JSON results into .NET objects  
  73.          SearchResult searchResult = Newtonsoft.Json.JsonConvert.DeserializeObject<SearchResult>(x.ToString());  
  74.          strb.AppendLine(string.Format(template, searchResult.Title, searchResult.Content, searchResult.Url));  
  75.      });  
  76.      return strb.ToString();  
  77.  }  
  78.  
  79.  #endregion  

输出结果

 

 

[csharp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. Title:<b>Paris Hilton</b> - Wikipedia, the free encyclopedia  
  2. Content: [1] In 2006, she released her debut album...  
  3. Url:http://en.wikipedia.org/wiki/Paris_Hilton  
  4.   
  5.   
  6. Title:<b>Paris Hilton</b>  
  7. Content: Self: Zoolander. Socialite <b>Paris Hilton</b>...  
  8. Url:http://www.imdb.com/name/nm0385296/  

5、利用Json.Linq序列化

 

可以突破实体类的限制,自由组合要序列化的值

 

[csharp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. public class Linq2Json  
  2. {  
  3.     #region GetJObject  
  4.   
  5.     //Parsing a JSON Object from text   
  6.     public Newtonsoft.Json.Linq.JObject GetJObject()  
  7.     {  
  8.         string json = @"{  
  9.                           CPU: \'Intel\',  
  10.                           Drives: [  
  11.                             \'DVD read/writer\',  
  12.                             \'500 gigabyte hard drive\'  
  13.                           ]  
  14.                         }";  
  15.         Newtonsoft.Json.Linq.JObject jobject = Newtonsoft.Json.Linq.JObject.Parse(json);  
  16.         return jobject;  
  17.     }  
  18.   
  19.     /*  
  20.      * //example:=> 
  21.      *  
  22.         Linq2Json l2j = new Linq2Json(); 
  23.         Newtonsoft.Json.Linq.JObject jobject = l2j.GetJObject2(Server.MapPath("json/Person.json")); 
  24.         //return Newtonsoft.Json.JsonConvert.SerializeObject(jobject, Newtonsoft.Json.Formatting.Indented); 
  25.         return jobject.ToString(); 
  26.      */  
  27.     //Loading JSON from a file  
  28.     public Newtonsoft.Json.Linq.JObject GetJObject2(string jsonPath)  
  29.     {  
  30.         using (System.IO.StreamReader reader = System.IO.File.OpenText(jsonPath))  
  31.         {  
  32.             Newtonsoft.Json.Linq.JObject jobject = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.Linq.JToken.ReadFrom(new Newtonsoft.Json.JsonTextReader(reader));  
  33.             return jobject;  
  34.         }  
  35.     }  
  36.   
  37.     //Creating JObject  
  38.     public Newtonsoft.Json.Linq.JObject GetJObject3()  
  39.     {  
  40.         List<Post> posts = GetPosts();  
  41.         Newtonsoft.Json.Linq.JObject jobject = Newtonsoft.Json.Linq.JObject.FromObject(new  
  42.         {  
  43.             channel = new  
  44.             {  
  45.                 title = "James Newton-King",  
  46.                 link = "http://james.newtonking.com",  
  47.                 description = "James Newton-King\'s blog.",  
  48.                 item =  
  49.                     from p in posts  
  50.                     orderby p.Title  
  51.                     select new  
  52.                     {  
  53.                         title = p.Title,  
  54.                         description = p.Description,  
  55.                         link = p.Link,  
  56.                         category = p.Category  
  57.                     }  
  58.             }  
  59.         });  
  60.   
  61.         return jobject;  
  62.     }  
  63.     /* 
  64.         { 
  65.             "channel": { 
  66.                 "title": "James Newton-King", 
  67.                 "link": "http://james.newtonking.com", 
  68.                 "description": "James Newton-King\'s blog.", 
  69.                 "item": [{ 
  70.                     "title": "jewron", 
  71.                     "description": "4546fds", 
  72.                     "link": "http://www.baidu.com", 
  73.                     "category": "jhgj" 
  74.                 }, 
  75.                 { 
  76.                     "title": "jofdsn", 
  77.                     "description": "mdsfan", 
  78.                     "link": "http://www.baidu.com", 
  79.                     "category": "6546" 
  80.                 }, 
  81.                 { 
  82.                     "title": "jokjn", 
  83.                     "description": "m3214an", 
  84.                     "link": "http://www.baidu.com", 
  85.                     "category": "hg425" 
  86.                 }, 
  87.                 { 
  88.                     "title": "jon", 
  89.                     "description": "man", 
  90.                     "link": "http://www.baidu.com", 
  91.                     "category": "goodman" 
  92.                 }] 
  93.             } 
  94.         } 
  95.      */  
  96.     //Creating JObject  
  97.     public Newtonsoft.Json.Linq.JObject GetJObject4()  
  98.     {  
  99.         List<Post> posts = GetPosts();  
  100.         Newtonsoft.Json.Linq.JObject rss = new Newtonsoft.Json.Linq.JObject(  
  101.                 new Newtonsoft.Json.Linq.JProperty("channel",  
  102.                     new Newtonsoft.Json.Linq.JObject(  
  103.                         new Newtonsoft.Json.Linq.JProperty("title", "James Newton-King"),  
  104.                         new Newtonsoft.Json.Linq.JProperty("link", "http://james.newtonking.com"),  
  105.                         new Newtonsoft.Json.Linq.JProperty("description", "James Newton-King\'s blog."),  
  106.                         new Newtonsoft.Json.Linq.JProperty("item",  
  107.                             new Newtonsoft.Json.Linq.JArray(  
  108.                                 from p in posts  
  109.                                 orderby p.Title  
  110.                                 select new Newtonsoft.Json.Linq.JObject(  
  111.                                     new Newtonsoft.Json.Linq.JProperty("title", p.Title),  
  112.                                     new Newtonsoft.Json.Linq.JProperty("description", p.Description),  
  113.                                     new Newtonsoft.Json.Linq.JProperty("link", p.Link),  
  114.                                     new Newtonsoft.Json.Linq.JProperty("category",  
  115.                                         new Newtonsoft.Json.Linq.JArray(  
  116.                                             from c in p.Category  
  117.                                             select new Newtonsoft.Json.Linq.JValue(c)  
  118.                                         )  
  119.                                     )  
  120.                                 )  
  121.                             )  
  122.                         )  
  123.                     )  
  124.                 )  
  125.             );  
  126.   
  127.         return rss;  
  128.     }  
  129.     /* 
  130.         { 
  131.             "channel": { 
  132.                 "title": "James Newton-King", 
  133.                 "link": "http://james.newtonking.com", 
  134.                 "description": "James Newton-King\'s blog.", 
  135.                 "item": [{ 
  136.                &nb

    以上是关于C# 解析JSON方法总结的主要内容,如果未能解决你的问题,请参考以下文章

    C#解析JSON字符串总结

    解析Exception和C#处理Exception的常用方法总结

    解析Exception和C#处理Exception的常用方法总结

    解析Exception和C#处理Exception的常用方法总结

    解析Exception和C#处理Exception的常用方法总结

    解析Exception和C#处理Exception的常用方法总结