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
根据自己需求,做些测试、修改、整理。
一、用JsonConvert序列化和反序列化。
实体类不用特殊处理,正常定义属性即可,控制属性是否被序列化参照高级用法1。
- public interface IPerson
- {
- string FirstName
- {
- get;
- set;
- }
- string LastName
- {
- get;
- set;
- }
- DateTime BirthDate
- {
- get;
- set;
- }
- }
- public class Employee : IPerson
- {
- public string FirstName
- {
- get;
- set;
- }
- public string LastName
- {
- get;
- set;
- }
- public DateTime BirthDate
- {
- get;
- set;
- }
- public string Department
- {
- get;
- set;
- }
- public string JobTitle
- {
- get;
- set;
- }
- public string NotSerialize { get; set; }
- }
- public class PersonConverter : Newtonsoft.Json.Converters.CustomCreationConverter<IPerson>
- {
- //重写abstract class CustomCreationConverter<T>的Create方法
- public override IPerson Create(Type objectType)
- {
- return new Employee();
- }
- }
- public class Product
- {
- public string Name { get; set; }
- public DateTime Expiry { get; set; }
- public Decimal Price { get; set; }
- public string[] Sizes { get; set; }
- public string NotSerialize { get; set; }
- }
1.序列化代码:
- #region 序列化 用JsonConvert
- public string TestJsonSerialize()
- {
- Product product = new Product();
- product.Name = "Apple";
- product.Expiry = DateTime.Now;//.AddDays(3).ToString("yyyy-MM-dd hh:mm:ss");
- product.Price = 3.99M;
- //string json = Newtonsoft.Json.JsonConvert.SerializeObject(product); //没有缩进输出
- string json = Newtonsoft.Json.JsonConvert.SerializeObject(product, Newtonsoft.Json.Formatting.Indented);//有缩进输出
- //string json = Newtonsoft.Json.JsonConvert.SerializeObject(
- // product,
- // Newtonsoft.Json.Formatting.Indented,
- // new Newtonsoft.Json.JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore }//参照高级用法中有关JsonSerializerSettings用法
- //);
- return json;
- }
- public string TestListJsonSerialize()
- {
- Product product = new Product();
- product.Name = "Apple";
- product.Expiry = DateTime.Now;//.AddDays(3).ToString("yyyy-MM-dd hh:mm:ss");
- product.Price = 3.99M;
- product.Sizes = new string[] { "Small", "Medium", "Large" };
- List<Product> plist = new List<Product>();
- plist.Add(product);
- plist.Add(product);
- string json = Newtonsoft.Json.JsonConvert.SerializeObject(plist, Newtonsoft.Json.Formatting.Indented);
- return json;
- }
- #endregion
2.反序列化代码:
- #region 反序列化 用JsonConvert
- public string TestJsonDeserialize()
- {
- string strjson = "{\\"Name\\":\\"Apple\\",\\"Expiry\\":\\"2014-05-03 10:20:59\\",\\"Price\\":3.99,\\"Sizes\\":[\\"Small\\",\\"Medium\\",\\"Large\\"]}";
- Product p = Newtonsoft.Json.JsonConvert.DeserializeObject<Product>(strjson);
- string template = @"
- Name:{0}
- Expiry:{1}
- Price:{2}
- Sizes:{3}
- ";
- return string.Format(template, p.Name, p.Expiry, p.Price.ToString(), string.Join(",", p.Sizes));
- }
- public string TestListJsonDeserialize()
- {
- string strjson = "{\\"Name\\":\\"Apple\\",\\"Expiry\\":\\"2014-05-03 10:20:59\\",\\"Price\\":3.99,\\"Sizes\\":[\\"Small\\",\\"Medium\\",\\"Large\\"]}";
- List<Product> plist = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Product>>(string.Format("[{0},{1}]", strjson, strjson));
- string template = @"
- Name:{0}
- Expiry:{1}
- Price:{2}
- Sizes:{3}
- ";
- System.Text.StringBuilder strb = new System.Text.StringBuilder();
- plist.ForEach(x =>
- strb.AppendLine(
- string.Format(template, x.Name, x.Expiry, x.Price.ToString(), string.Join(",", x.Sizes))
- )
- );
- return strb.ToString();
- }
- #endregion
3.自定义序列化,使用实体类中定义的PersonConverter,每反序列化一次实体时会调用一次PersonConverter,还没想清楚如何用。
- #region 自定义反序列化
- public string TestListCustomDeserialize()
- {
- 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\\" } ] ";
- List<IPerson> people = Newtonsoft.Json.JsonConvert.DeserializeObject<List<IPerson>>(strJson, new PersonConverter());
- IPerson person = people[0];
- string template = @"
- 当前List<IPerson>[x]对象类型:{0}
- FirstName:{1}
- LastName:{2}
- BirthDate:{3}
- Department:{4}
- JobTitle:{5}
- ";
- System.Text.StringBuilder strb = new System.Text.StringBuilder();
- people.ForEach(x =>
- strb.AppendLine(
- string.Format(
- template,
- person.GetType().ToString(),
- x.FirstName,
- x.LastName,
- x.BirthDate.ToString(),
- ((Employee)x).Department,
- ((Employee)x).JobTitle
- )
- )
- );
- return strb.ToString();
- }
- #endregion
4、获取Json字符串中部分内容
- #region Serializing Partial JSON Fragment Example
- public class SearchResult
- {
- public string Title { get; set; }
- public string Content { get; set; }
- public string Url { get; set; }
- }
- public string SerializingJsonFragment()
- {
- #region
- string googleSearchText = @"{
- \'responseData\': {
- \'results\': [{
- \'GsearchResultClass\': \'GwebSearch\',
- \'unescapedUrl\': \'http://en.wikipedia.org/wiki/Paris_Hilton\',
- \'url\': \'http://en.wikipedia.org/wiki/Paris_Hilton\',
- \'visibleUrl\': \'en.wikipedia.org\',
- \'cacheUrl\': \'http://www.google.com/search?q=cache:TwrPfhd22hYJ:en.wikipedia.org\',
- \'title\': \'<b>Paris Hilton</b> - Wikipedia, the free encyclopedia\',
- \'titleNoFormatting\': \'Paris Hilton - Wikipedia, the free encyclopedia\',
- \'content\': \'[1] In 2006, she released her debut album...\'
- },
- {
- \'GsearchResultClass\': \'GwebSearch\',
- \'unescapedUrl\': \'http://www.imdb.com/name/nm0385296/\',
- \'url\': \'http://www.imdb.com/name/nm0385296/\',
- \'visibleUrl\': \'www.imdb.com\',
- \'cacheUrl\': \'http://www.google.com/search?q=cache:1i34KkqnsooJ:www.imdb.com\',
- \'title\': \'<b>Paris Hilton</b>\',
- \'titleNoFormatting\': \'Paris Hilton\',
- \'content\': \'Self: Zoolander. Socialite <b>Paris Hilton</b>...\'
- }],
- \'cursor\': {
- \'pages\': [{
- \'start\': \'0\',
- \'label\': 1
- },
- {
- \'start\': \'4\',
- \'label\': 2
- },
- {
- \'start\': \'8\',
- \'label\': 3
- },
- {
- \'start\': \'12\',
- \'label\': 4
- }],
- \'estimatedResultCount\': \'59600000\',
- \'currentPageIndex\': 0,
- \'moreResultsUrl\': \'http://www.google.com/search?oe=utf8&ie=utf8...\'
- }
- },
- \'responseDetails\': null,
- \'responseStatus\': 200
- }";
- #endregion
- Newtonsoft.Json.Linq.JObject googleSearch = Newtonsoft.Json.Linq.JObject.Parse(googleSearchText);
- // get JSON result objects into a list
- List<Newtonsoft.Json.Linq.JToken> listJToken = googleSearch["responseData"]["results"].Children().ToList();
- System.Text.StringBuilder strb = new System.Text.StringBuilder();
- string template = @"
- Title:{0}
- Content: {1}
- Url:{2}
- ";
- listJToken.ForEach(x =>
- {
- // serialize JSON results into .NET objects
- SearchResult searchResult = Newtonsoft.Json.JsonConvert.DeserializeObject<SearchResult>(x.ToString());
- strb.AppendLine(string.Format(template, searchResult.Title, searchResult.Content, searchResult.Url));
- });
- return strb.ToString();
- }
- #endregion
输出结果
- Title:<b>Paris Hilton</b> - Wikipedia, the free encyclopedia
- Content: [1] In 2006, she released her debut album...
- Url:http://en.wikipedia.org/wiki/Paris_Hilton
- Title:<b>Paris Hilton</b>
- Content: Self: Zoolander. Socialite <b>Paris Hilton</b>...
- Url:http://www.imdb.com/name/nm0385296/
5、利用Json.Linq序列化
可以突破实体类的限制,自由组合要序列化的值
- public class Linq2Json
- {
- #region GetJObject
- //Parsing a JSON Object from text
- public Newtonsoft.Json.Linq.JObject GetJObject()
- {
- string json = @"{
- CPU: \'Intel\',
- Drives: [
- \'DVD read/writer\',
- \'500 gigabyte hard drive\'
- ]
- }";
- Newtonsoft.Json.Linq.JObject jobject = Newtonsoft.Json.Linq.JObject.Parse(json);
- return jobject;
- }
- /*
- * //example:=>
- *
- Linq2Json l2j = new Linq2Json();
- Newtonsoft.Json.Linq.JObject jobject = l2j.GetJObject2(Server.MapPath("json/Person.json"));
- //return Newtonsoft.Json.JsonConvert.SerializeObject(jobject, Newtonsoft.Json.Formatting.Indented);
- return jobject.ToString();
- */
- //Loading JSON from a file
- public Newtonsoft.Json.Linq.JObject GetJObject2(string jsonPath)
- {
- using (System.IO.StreamReader reader = System.IO.File.OpenText(jsonPath))
- {
- Newtonsoft.Json.Linq.JObject jobject = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.Linq.JToken.ReadFrom(new Newtonsoft.Json.JsonTextReader(reader));
- return jobject;
- }
- }
- //Creating JObject
- public Newtonsoft.Json.Linq.JObject GetJObject3()
- {
- List<Post> posts = GetPosts();
- Newtonsoft.Json.Linq.JObject jobject = Newtonsoft.Json.Linq.JObject.FromObject(new
- {
- channel = new
- {
- title = "James Newton-King",
- link = "http://james.newtonking.com",
- description = "James Newton-King\'s blog.",
- item =
- from p in posts
- orderby p.Title
- select new
- {
- title = p.Title,
- description = p.Description,
- link = p.Link,
- category = p.Category
- }
- }
- });
- return jobject;
- }
- /*
- {
- "channel": {
- "title": "James Newton-King",
- "link": "http://james.newtonking.com",
- "description": "James Newton-King\'s blog.",
- "item": [{
- "title": "jewron",
- "description": "4546fds",
- "link": "http://www.baidu.com",
- "category": "jhgj"
- },
- {
- "title": "jofdsn",
- "description": "mdsfan",
- "link": "http://www.baidu.com",
- "category": "6546"
- },
- {
- "title": "jokjn",
- "description": "m3214an",
- "link": "http://www.baidu.com",
- "category": "hg425"
- },
- {
- "title": "jon",
- "description": "man",
- "link": "http://www.baidu.com",
- "category": "goodman"
- }]
- }
- }
- */
- //Creating JObject
- public Newtonsoft.Json.Linq.JObject GetJObject4()
- {
- List<Post> posts = GetPosts();
- Newtonsoft.Json.Linq.JObject rss = new Newtonsoft.Json.Linq.JObject(
- new Newtonsoft.Json.Linq.JProperty("channel",
- new Newtonsoft.Json.Linq.JObject(
- new Newtonsoft.Json.Linq.JProperty("title", "James Newton-King"),
- new Newtonsoft.Json.Linq.JProperty("link", "http://james.newtonking.com"),
- new Newtonsoft.Json.Linq.JProperty("description", "James Newton-King\'s blog."),
- new Newtonsoft.Json.Linq.JProperty("item",
- new Newtonsoft.Json.Linq.JArray(
- from p in posts
- orderby p.Title
- select new Newtonsoft.Json.Linq.JObject(
- new Newtonsoft.Json.Linq.JProperty("title", p.Title),
- new Newtonsoft.Json.Linq.JProperty("description", p.Description),
- new Newtonsoft.Json.Linq.JProperty("link", p.Link),
- new Newtonsoft.Json.Linq.JProperty("category",
- new Newtonsoft.Json.Linq.JArray(
- from c in p.Category
- select new Newtonsoft.Json.Linq.JValue(c)
- )
- )
- )
- )
- )
- )
- )
- );
- return rss;
- }
- /*
- {
- "channel": {
- "title": "James Newton-King",
- "link": "http://james.newtonking.com",
- "description": "James Newton-King\'s blog.",
- "item": [{
- &nb
以上是关于C# 解析JSON方法总结的主要内容,如果未能解决你的问题,请参考以下文章
解析Exception和C#处理Exception的常用方法总结
解析Exception和C#处理Exception的常用方法总结
解析Exception和C#处理Exception的常用方法总结