1. 程式人生 > >C# 解析JSON方法總結

C# 解析JSON方法總結

主要參考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": [{
                        "title": "jewron",
                        "description": "4546fds",
                        "link": "http://www.baidu.com",
                        "category": ["j", "h", "g", "j"]
                    },
                    {
                        "title": "jofdsn",
                        "description": "mdsfan",
                        "link": "http://www.baidu.com",
                        "category": ["6", "5", "4", "6"]
                    },
                    {
                        "title": "jokjn",
                        "description": "m3214an",
                        "link": "http://www.baidu.com",
                        "category": ["h", "g", "4", "2", "5"]
                    },
                    {
                        "title": "jon",
                        "description": "man",
                        "link": "http://www.baidu.com",
                        "category": ["g", "o", "o", "d", "m", "a", "n"]
                    }]
                }
            }
         */

        public class Post
        {
            public string Title { get; set; }
            public string Description { get; set; }
            public string Link { get; set; }
            public string Category { get; set; }
        }
        private List<Post> GetPosts()
        {
            List<Post> listp = new List<Post>()
            {
                new Post{Title="jon",Description="man",Link="http://www.baidu.com",Category="goodman"},
                new Post{Title="jofdsn",Description="mdsfan",Link="http://www.baidu.com",Category="6546"},
                new Post{Title="jewron",Description="4546fds",Link="http://www.baidu.com",Category="jhgj"},
                new Post{Title="jokjn",Description="m3214an",Link="http://www.baidu.com",Category="hg425"}
            };
            return listp;
        }

        #endregion

        #region GetJArray
        /*
         * //example:=>
         * 
            Linq2Json l2j = new Linq2Json();
            Newtonsoft.Json.Linq.JArray jarray = l2j.GetJArray();
            return Newtonsoft.Json.JsonConvert.SerializeObject(jarray, Newtonsoft.Json.Formatting.Indented);
            //return jarray.ToString();
         */
        //Parsing a JSON Array from text 
        public Newtonsoft.Json.Linq.JArray GetJArray()
        {
            string json = @"[
                              'Small',
                              'Medium',
                              'Large'
                            ]";

            Newtonsoft.Json.Linq.JArray jarray = Newtonsoft.Json.Linq.JArray.Parse(json);
            return jarray;
        }

        //Creating JArray
        public Newtonsoft.Json.Linq.JArray GetJArray2()
        {
            Newtonsoft.Json.Linq.JArray array = new Newtonsoft.Json.Linq.JArray();
            Newtonsoft.Json.Linq.JValue text = new Newtonsoft.Json.Linq.JValue("Manual text");
            Newtonsoft.Json.Linq.JValue date = new Newtonsoft.Json.Linq.JValue(new DateTime(2000, 5, 23));
            //add to JArray
            array.Add(text);
            array.Add(date);

            return array;
        }

        #endregion

    }

使用方式
            Linq2Json l2j = new Linq2Json();
            Newtonsoft.Json.Linq.JObject jarray = l2j.GetJObject4();
            return jarray.ToString();


二、高階用法

1.忽略某些屬性

當實體類中定義了很多屬性,但序列化時只想針對某些屬性時可以採用此方式。這種需求還可以細分為執行時不同時刻參與序列化屬性集合不固定和固定兩種情況。

1)能解決參與序列化屬性集合固定的情況

OptOut     預設值,類中所有公有成員會被序列化,如果不想被序列化,可以用特性JsonIgnore
OptIn     預設情況下,所有的成員不會被序列化,類中的成員只有標有特性JsonProperty的才會被序列化,當類的成員很多,但客戶端僅僅需要一部分資料時,很有用

僅需要姓名屬性:

    [JsonObject(MemberSerialization.OptIn)]
    public class Person
    {
        public int Age { get; set; }

        [JsonProperty]
        public string Name { get; set; }

        public string Sex { get; set; }

        public bool IsMarry { get; set; }

        public DateTime Birthday { get; set; }
    }
輸出結果


不需要是否結婚屬性

    [JsonObject(MemberSerialization.OptOut)]
    public class Person
    {
        public int Age { get; set; }

        public string Name { get; set; }

        public string Sex { get; set; }

        [JsonIgnore]
        public bool IsMarry { get; set; }

        public DateTime Birthday { get; set; }
    }
輸出結果


通過上面的例子可以看到,要實現不返回某些屬性的需求很簡單。1.在實體類上加上[JsonObject(MemberSerialization.OptOut)] 2.在不需要返回的屬性上加上 [JsonIgnore]說明。

2)能解決參與序列化屬性集合不固定的情況

方法1:通過設定忽略預設值屬性方式。有點傻。

方法2:繼承預設的DefaultContractResolver類,傳入需要輸出的屬性。

2、預設值

可以設定某個屬性的預設值,然後序列化或反序列化時自動判斷是否預設值,然後選擇是否忽略對具有預設值的屬性序列化或反序列化。

序列化時想忽略預設值屬性可以通過JsonSerializerSettings.DefaultValueHandling來確定,該值為列舉值。

DefaultValueHandling.Ignore     序列化和反序列化時,忽略預設值
DefaultValueHandling.Include    序列化和反序列化時,包含預設值

[DefaultValue(10)]
 public int Age { get; set; }
 Person p = new Person { Age = 10, Name = "張三丰", Sex = "男", IsMarry = false, Birthday = new DateTime(1991, 1, 2) };
 JsonSerializerSettings jsetting=new JsonSerializerSettings();
 jsetting.DefaultValueHandling=DefaultValueHandling.Ignore;
 Console.WriteLine(JsonConvert.SerializeObject(p, Formatting.Indented, jsetting));
輸出結果

3、空值

與預設值類似,可以選擇是否忽略對空值的屬性序列化或反序列化。

序列化時需要忽略值為NULL的屬性,可以通過JsonSerializerSettings.NullValueHandling來確定,另外通過JsonSerializerSettings設定屬性是對序列化過程中所有屬性生效的,想單獨對某一個屬性生效可以使用JsonProperty,下面將分別展示兩個方式。

1)JsonSerializerSettings.NullValueHandling方式,會忽略實體中全部空值引數

Person p = new Person { room=null,Age = 10, Name = "張三丰", Sex = "男", IsMarry = false, Birthday = new DateTime(1991, 1, 2) };
 JsonSerializerSettings jsetting=new JsonSerializerSettings();
 jsetting.NullValueHandling = NullValueHandling.Ignore;
 Console.WriteLine(JsonConvert.SerializeObject(p, Formatting.Indented, jsetting));

上例中不會序列化room。

2)JsonProperty,忽略特定的屬性

[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
 public Room room { get; set; }

4、支援非公共屬性

[JsonProperty]
 private int Height { get; set; }

5、日期

對於Dateime型別日期的格式化就比較麻煩了,系統自帶的會格式化成iso日期標準,但是實際使用過程中大多數使用的可能是yyyy-MM-dd 或者yyyy-MM-dd HH:mm:ss兩種格式的日期,解決辦法是可以將DateTime型別改成string型別自己格式化好,然後在序列化。如果不想修改程式碼,可以採用下面方案實現。

      Json.Net提供了IsoDateTimeConverter日期轉換這個類,可以通過JsnConverter實現相應的日期轉換

   [JsonConverter(typeof(IsoDateTimeConverter))]
    public DateTime Birthday { get; set; }
但是IsoDateTimeConverter日期格式不是我們想要的,我們可以繼承該類實現自己的日期
    public class ChinaDateTimeConverter : DateTimeConverterBase
    {
        private static IsoDateTimeConverter dtConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd" };

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            return dtConverter.ReadJson(reader, objectType, existingValue, serializer);
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            dtConverter.WriteJson(writer, value, serializer);
        }
    }

自己實現了一個yyyy-MM-dd格式化轉換類,可以看到只是初始化IsoDateTimeConverter時給的日期格式為yyyy-MM-dd即可,下面看下效果
[JsonConverter(typeof(ChinaDateTimeConverter))]
public DateTime Birthday { get; set; }

日期處理也可以通過設定全域性JsonConvert.DefaultSettings,設定JsonSerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"。

6、自定義序列化時的屬性名稱

等同於DataMember中PropertyName作用。

實體中定義的屬性名可能不是自己想要的名稱,但是又不能更改實體定義,這個時候可以自定義序列化欄位名稱。

     [JsonProperty(PropertyName = "CName")]
     public string Name { get; set; }

7、列舉值的自定義格式化

預設情況下對於實體裡面的列舉型別系統是格式化成改列舉對應的整型數值,那如果需要格式化成列舉對應的字元怎麼處理呢?

    public enum NotifyType
    {
        /// <summary>
        /// Emil傳送
        /// </summary>
        Mail=0,

        /// <summary>
        /// 簡訊傳送
        /// </summary>
        SMS=1
    }
    public class TestEnmu
    {
        /// <summary>
        /// 訊息傳送型別
        /// </summary>
        [JsonConverter(typeof(StringEnumConverter))]
        public NotifyType Type { get; set; }
    }
輸出結果


8、自定義型別轉換

預設情況下對於實體裡面的Boolean系統是格式化成true或者false,對於true轉成"是" false轉成"否"這種需求改怎麼實現了?我們可以自定義型別轉換實現該需求,下面看例項

    public class BoolConvert : JsonConverter
    {
        private string[] arrBString { get; set; }

        public BoolConvert()
        {
            arrBString = "是,否".Split(',');
        }

        /// <summary>
        /// 建構函式
        /// </summary>
        /// <param name="BooleanString">將bool值轉換成的字串值</param>
        public BoolConvert(string BooleanString)
        {
            if (string.IsNullOrEmpty(BooleanString))
            {
                throw new ArgumentNullException();
            }
            arrBString = BooleanString.Split(',');
            if (arrBString.Length != 2)
            {
                throw new ArgumentException("BooleanString格式不符合規定");
            }
        }


        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            bool isNullable = IsNullableType(objectType);
            Type t = isNullable ? Nullable.GetUnderlyingType(objectType) : objectType;

            if (reader.TokenType == JsonToken.Null)
            {
                if (!IsNullableType(objectType))
                {
                    throw new Exception(string.Format("不能轉換null value to {0}.", objectType));
                }

                return null;
            }

            try
            {
                if (reader.TokenType == JsonToken.String)
                {
                    string boolText = reader.Value.ToString();
                    if (boolText.Equals(arrBString[0], StringComparison.OrdinalIgnoreCase))
                    {
                        return true;
                    }
                    else if (boolText.Equals(arrBString[1], StringComparison.OrdinalIgnoreCase))
                    {
                        return false;
                    }
                }

                if (reader.TokenType == JsonToken.Integer)
                {
                    //數值
                    return Convert.ToInt32(reader.Value) == 1;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Error converting value {0} to type '{1}'", reader.Value, objectType));
            }
            throw new Exception(string.Format("Unexpected token {0} when parsing enum", reader.TokenType));
        }

        /// <summary>
        /// 判斷是否為Bool型別
        /// </summary>
        /// <param name="objectType">型別</param>
        /// <returns>為bool型別則可以進行轉換</returns>
        public override bool CanConvert(Type objectType)
        {
            return true;
        }


        public bool IsNullableType(Type t)
        {
            if (t == null)
            {
                throw new ArgumentNullException("t");
            }
            return (t.BaseType.FullName=="System.ValueType" && t.GetGenericTypeDefinition() == typeof(Nullable<>));
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
            {
                writer.WriteNull();
                return;
            }

            bool bValue = (bool)value;

            if (bValue)
            {
                writer.WriteValue(arrBString[0]);
            }
            else
            {
                writer.WriteValue(arrBString[1]);
            }
        }
    }

自定義了BoolConvert型別,繼承自JsonConverter。建構函式引數BooleanString可以讓我們自定義將true false轉換成相應字串。下面看實體裡面怎麼使用這個自定義轉換型別
    public class Person
    {
        [JsonConverter(typeof(BoolConvert))]
        public bool IsMarry { get; set; }
    }


相應的有什麼個性化的轉換需求,都可以使用自定義轉換型別的方式實現。

9、全域性序列化設定

對全域性預設JsonSerializerSettings設定,省卻每處都要相同設定程式碼的麻煩。

   Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings();
   JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
   {
    //日期型別預設格式化處理
     setting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
      setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";

    //空值處理
      setting.NullValueHandling = NullValueHandling.Ignore;

      //高階用法九中的Bool型別轉換 設定
      setting.Converters.Add(new BoolConvert("是,否"));

      return setting;
   });