本文介绍通过第三方库Newtonsoft.Json来操作json数据。

官方文档

http://www.newtonsoft.com/json/help/html/Introduction.htm

JsonConvert

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;

namespace ConsoleApplication1
{
    class Program
    {

        public class Product
        {
            public string name;
            public DateTime time;
            public float price;
            public string[] desc;
        }


        static void Main(string[] args)
        {
            Product product = new Product();
            product.name = "zk";
            product.time = new DateTime();
            product.price = 19f;
            product.desc = new string[] {"big", "medium", "small"};

            string output = JsonConvert.SerializeObject(product);

            Console.WriteLine(output);

            Product newProduct = JsonConvert.DeserializeObject<Product>(output);

            Console.WriteLine(newProduct.name);
        }
    }
}

JsonSerializer

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;

namespace ConsoleApplication1
{
    class Program
    {

        public class Product
        {
            public string name;
            public DateTime time;

            public override string ToString()
            {
                return string.Format("Name: {0}, Time: {1}", name, time);
            }
        }


        static void Main(string[] args)
        {
            Product product = new Product();
            product.name = "zzz";
            product.time = new DateTime();

            JsonSerializer serial = new JsonSerializer();

            using (StreamWriter sw = new StreamWriter(System.Environment.CurrentDirectory + "\\" + "json.txt"))
            {
                serial.Serialize(sw, product);
            }
        }
    }
}

 对枚举的操作

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;

namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {

            List<StringComparison> compar = new List<StringComparison>
            {
                StringComparison.CurrentCulture,
                StringComparison.Ordinal
            };

            string output = JsonConvert.SerializeObject(compar);

            Console.WriteLine(output);

            output = JsonConvert.SerializeObject(compar, new StringEnumConverter());

            Console.WriteLine(output);

            List<StringComparison> compar1 = JsonConvert.DeserializeObject<List<StringComparison> >(output, new StringEnumConverter());

            Console.WriteLine(
                string.Join(",", compar1.Select(
                c => c.ToString()).ToArray()
                )
                );
        }
    }
}

 

对Dataset的操作

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;

namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {
            DataSet dataSet = new DataSet("zk");
            dataSet.Namespace = "network";

            DataTable table = new DataTable();
            table.TableName = "test";
            DataColumn idColumn = new DataColumn("id", typeof (int));
            idColumn.AutoIncrement = true;

            DataColumn itemColumn = new DataColumn("item");
            table.Columns.Add(idColumn);
            table.Columns.Add(itemColumn);

            dataSet.Tables.Add(table);

            for (int i = 0; i < 3; i++)
            {
                DataRow row = table.NewRow();
                row["item"] = "item" + i;
                table.Rows.Add(row);
            }

            dataSet.AcceptChanges();

            string res = JsonConvert.SerializeObject(dataSet, Formatting.Indented);

            Console.WriteLine(res);

        }
    }
}

 

对JRaw的操作

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;

namespace ConsoleApplication1
{
    class Program
    {

        public class Test
        {
            public JRaw On { get; set; }
            public JRaw Off { get; set; }
        }

        public class Test1
        {
            public string On { get; set; }
            public string Off { get; set; }
        }


        static void Main(string[] args)
        {

            Test test = new Test
            {
                On = new JRaw("On"),
                Off = new JRaw("Off")
            };

            Test1 test1 = new Test1
            {
                On = "On",
                Off = "Off"
            };

            string str = JsonConvert.SerializeObject(test, Formatting.Indented);
            Console.WriteLine(str);

               string str1 = JsonConvert.SerializeObject(test1, Formatting.Indented);
            Console.WriteLine(str);
        }
    }
}

序列化的条件属性

  需要构造一个函数返回bool,函数名字必须为”ShouldSerialize“ + 属性名字,以下例子Off属性永远都不会序列化。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;

namespace ConsoleApplication1
{
    class Program
    {

        public class Test
        {
            public JRaw On { get; set; }
            public JRaw Off { get; set; }

            public bool ShouldSerializeOff()
            {
                return false;
            }
        }



        static void Main(string[] args)
        {

            Test test = new Test
            {
                On = new JRaw("On"),
                Off = new JRaw("Off")
            };

          

            string str = JsonConvert.SerializeObject(test, Formatting.Indented);
            Console.WriteLine(str);

        }
    }
}

 反序列化对象

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;

namespace ConsoleApplication1
{
    class Program
    {

        public class Account
        {
            public string str
            {
                get;
                set;
            }
        }



        static void Main(string[] args)
        {

            string str = @"{
                'str' :'zzzzz'
}";

            Account account = JsonConvert.DeserializeObject<Account>(str);

            Console.WriteLine(account.str);

        }
    }
}

 反序列化集合

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string json = @"['zk', 'afdf', 'afdf']";

            List<string> res = JsonConvert.DeserializeObject<List<string>>(json);
            Console.WriteLine(string.Join(", ", res.ToArray()));
        }
    }
}

反序列化字典

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string json = @"{'href':'index.aspx',
'target':'newpage'}";

            Dictionary<string, string> html = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

            Console.WriteLine(html["href"]);
            Console.WriteLine(html["target"]);
        }
    }
}

反序列化匿名对象

 

using System;
using System.Collections.Generic;
using Newtonsoft.Json;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var defi = new {name = ""};
            var json = @"{'name':'zk'}";
            var customer = JsonConvert.DeserializeAnonymousType(json, defi);
            Console.WriteLine(customer.name);
        }
    }
}

 反序列化dataset

 

using System;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string json = @"{
        'Table':[
            {
            'id':0,
'item':'tem0'
},
{
    'id':1,
    'item':'tem1'
}
]
}";

            DataSet dataset = JsonConvert.DeserializeObject<DataSet>(json);
            DataTable dataTable = dataset.Tables["Table"];
            Console.WriteLine(dataTable.Rows.Count);

            foreach (DataRow row in dataTable.Rows)
            {
                Console.WriteLine(row["id"] + "-" + row["item"]);
            }

        }
    }
}

 填充已有对象

 

using System;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;


namespace ConsoleApplication1
{
    class Program
    {

        public class Account
        {
            public string Email
            {
                get;
                set;
            }

            public bool Active
            {
                get;
                set;
            }
        }

        static void Main(string[] args)
        {
            Account account = new Account
            {
                Email = "xx@xx.com",
                Active = false
            };

            string json = @"{
        'Active':true,
'Email':'zkzk945@126.com'
}";

            JsonConvert.PopulateObject(json, account);
            Console.WriteLine(account.Email);
            Console.WriteLine(account.Active);
        }
    }
}

 允许反序列化私有构造函数对象

 

using System;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;


namespace ConsoleApplication1
{
    class Program
    {
        public class Website
        {
            public string url
            {
                get;
                set;
            }

            private Website()
            {
                
            }

            public Website(Website website)
            {
                if (website == null)
                {
                    throw new ArgumentNullException();
                }

                url = website.url;
            }

        }
        
        static void Main(string[] args)
        {
            string json = @"{
    'url':'http://www.baidu.com'
}";

            try
            {
                JsonConvert.DeserializeObject<Website>(json);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Website website = JsonConvert.DeserializeObject<Website>(json, new JsonSerializerSettings()
            {
                ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
            }
                );

            Console.WriteLine(website.url);
        }
    }
}

反序列化时不复制已有数据

 

using System;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;


namespace ConsoleApplication1
{
    internal class Program
    {
        public class Test
        {
            public List<string> Str { get; set; }

            public Test()
            {
                Str = new List<string>
                {
                    "zk",
                    "zk1",
                    "zk3"
                };
            }
        }

        private static void Main(string[] args)
        {
            string json = @"{
            'Str':
[
    'zk',
'zk1',
'zk4'
]
}";

            Test test = JsonConvert.DeserializeObject<Test>(json);

            foreach (string str in test.Str)
            {
                Console.WriteLine(str);
            }

           Test test1 = JsonConvert.DeserializeObject<Test>(json,
                new JsonSerializerSettings()
                {
                    ObjectCreationHandling = ObjectCreationHandling.Replace
                }
                );

            Console.WriteLine("-------------");

            foreach (string str in test1.Str)
            {
                Console.WriteLine(str);
            }

        }
    }
}

 序列化时忽略为默认值的字段

 

using System;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;


namespace ConsoleApplication1
{
    internal class Program
    {
        public class Test
        {
            public int Age
            {
                get;
                set;
            }
        }

        private static void Main(string[] args)
        {
            Test test = new Test();

            string str = JsonConvert.SerializeObject(test, Formatting.Indented);

            Console.WriteLine(str);

            string str1 = JsonConvert.SerializeObject(test, Formatting.Indented,
                new JsonSerializerSettings()
                {
                    DefaultValueHandling = DefaultValueHandling.Ignore
                });

            Console.WriteLine(str1);
        }
    }
}

 反序列化时对于没有的字段怎么处理

 

using System;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;


namespace ConsoleApplication1
{
    internal class Program
    {
        public class Test
        {
            public int Age
            {
                get;
                set;
            }
        }

        private static void Main(string[] args)
        {
            string json = @"{
        'Age':12,
        'Name':'zk'
}";

            try
            {
                JsonConvert.DeserializeObject<Test>(json,
                    new JsonSerializerSettings()
                    {
                        MissingMemberHandling = MissingMemberHandling.Error
                    }
                    );
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

            }

        }
    }
}

 为NULL的字段将不会进行序列化

 

using System;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;


namespace ConsoleApplication1
{
    internal class Program
    {
        public class Test
        {
            public int Age
            {
                get;
                set;
            }

            public string Name
            {
                get;
                set;
            }
        }

        private static void Main(string[] args)
        {
            Test test = new Test();

            string res = JsonConvert.SerializeObject(test, Formatting.Indented);

            Console.WriteLine(res);


            string res1 = JsonConvert.SerializeObject(test, Formatting.Indented,
                new JsonSerializerSettings()
                {
                    NullValueHandling = NullValueHandling.Ignore
                });

            Console.WriteLine(res1);
        }
    }
}

忽略序列化时的循环引用错误

 

using System;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;


namespace ConsoleApplication1
{
    internal class Program
    {
        public class Test
        {
            public int Age
            {
                get;
                set;
            }

            public Test CTest
            {
                get;
                set;
            }
        }

        private static void Main(string[] args)
        {
            Test test = new Test();
            Test test1 = new Test();
            test.CTest = test1;
            test1.CTest = test1;

            string res = JsonConvert.SerializeObject(test, Formatting.Indented,
                new JsonSerializerSettings()
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                });

            Console.WriteLine(res);
        }
    }
}

对引用的处理方式

  不进行处理会报错

using System;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;


namespace ConsoleApplication1
{
    internal class Program
    {
        public class Test
        {
            public int Age
            {
                get;
                set;
            }

            public Test CTest
            {
                get;
                set;
            }
        }

        private static void Main(string[] args)
        {
            Test test = new Test();
            Test test1 = new Test();
            test.CTest = test1;
            test1.CTest = test1;


            string res = JsonConvert.SerializeObject(test, Formatting.Indented,
                new JsonSerializerSettings()
                {
                    PreserveReferencesHandling = PreserveReferencesHandling.All
                });

            Console.WriteLine(res);
        }
    }
}

 对Datetime的序列化处理

using System;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;


namespace ConsoleApplication1
{
    internal class Program
    {

        private static void Main(string[] args)
        {
            DateTime time = new DateTime(2012, 12, 12);

            string res = JsonConvert.SerializeObject(time, Formatting.Indented,
                new JsonSerializerSettings()
                {
                    DateFormatHandling = DateFormatHandling.IsoDateFormat
                });

            Console.WriteLine(res);
        }
    }
}

对Datetime的时区处理

 

using System;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;


namespace ConsoleApplication1
{
    internal class Program
    {

        private static void Main(string[] args)
        {
            DateTime time = new DateTime(2012, 12, 12);

            string res = JsonConvert.SerializeObject(time, Formatting.Indented,
                new JsonSerializerSettings()
                {
                    DateTimeZoneHandling = DateTimeZoneHandling.Unspecified
                });

            Console.WriteLine(res);
        }
    }
}

序列化时加上type信息

using System;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;


namespace ConsoleApplication1
{
    internal class Program
    {

        public class Test
        {
            public int Age
            {
                get;
                set;
            }
        }

        private static void Main(string[] args)
        {
            Test test = new Test();

            string res = JsonConvert.SerializeObject(test, Formatting.Indented,
                new JsonSerializerSettings()
                {
                    TypeNameHandling = TypeNameHandling.All
                });

            Console.WriteLine(res);
        }
    }
}

打开序列化的调试信息

 

using System;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;


namespace ConsoleApplication1
{
    internal class Program
    {

    public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public string FullName
    {
        get { return FirstName + " " + LastName; }
    }
}
        private static void Main(string[] args)
        {
            Person person = new Person
            {
                FirstName = "z",
                LastName = "k"
            };

            MemoryTraceWriter trace = new MemoryTraceWriter();

            string res = JsonConvert.SerializeObject(person, Formatting.Indented,
                new JsonSerializerSettings()
                {
                    TraceWriter = trace
                });

            Console.WriteLine(res);
            Console.WriteLine(trace);

        }
    }
}

 自己处理错误

 

using System;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;


namespace ConsoleApplication1
{
    internal class Program
    {
        public class Person
        {
            public int Age
            {
                get;
                set;
            }

            public DateTime Time
            {
                get;
                set;
            }
        }

        private static void Main(string[] args)
        {
            Person person = JsonConvert.DeserializeObject<Person>(
                @"{'Age':'12',
                    'Time':13
}", new JsonSerializerSettings()
                {
                    Error = delegate(object sender, ErrorEventArgs args1)
                    {
                        args1.ErrorContext.Handled = true;
                    }
                }
                );

            Console.WriteLine(person.Age);
        }
    }
}

反序列化的最大深度

 

using System;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;


namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            
            string json = @"[
  [
    [
      '1',
      'Two',
      'III'
    ]
  ]
]";

            try
            {
                JsonConvert.DeserializeObject<List<IList<IList<string>>>>(json, new JsonSerializerSettings
                {
                    MaxDepth = 2
                });
            }
            catch (JsonReaderException ex)
            {
                Console.WriteLine(ex.Message);
                // The reader's MaxDepth of 2 has been exceeded. Path '[0][0]', line 3, position 12.
            }
        }
    }
}

自定义Custom JsonConverter

暂无

 

自定义Custom IContractResolver

暂无

 

自定义 Custom ITraceWriter

暂无

 

自定义Custom SerializationBinder

暂无

 

构造函数属性JsonConstructorAttribute

 

using System;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;


namespace ConsoleApplication1
{
    internal class Program
    {
       public class User
{
    public string UserName { get; private set; }
    public bool Enabled { get; private set; }

    public User()
    {
    }

    [JsonConstructor]
    public User(string userName, bool enabled)
    {
        UserName = userName;
        Enabled = enabled;
    }
}
        private static void Main(string[] args)
        {
            
        string json = @"{
  'UserName': 'domain\\username',
  'Enabled': true
}";

User user = JsonConvert.DeserializeObject<User>(json);

Console.WriteLine(user.UserName);
// domain\username
        }
    }
}

类上的转化属性

  决定类怎么被序列化

using System;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;


namespace ConsoleApplication1
{
    internal class Program
    {
        public class UserConverter : JsonConverter
        {
            public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            {
                User user = (User) value;

                writer.WriteValue(user.UserName);
            }

            public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
                JsonSerializer serializer)
            {
                User user = new User();
                user.UserName = (string) reader.Value;

                return user;
            }

            public override bool CanConvert(Type objectType)
            {
                return objectType == typeof (User);
            }
        }

        [JsonConverter(typeof(UserConverter))]
        public class User
        {
            public string UserName { get; set; }
        }

        private static void Main(string[] args)
        {
            User user = new User
            {
                UserName = @"domain\username"
            };

            string json = JsonConvert.SerializeObject(user, Formatting.Indented);

            Console.WriteLine(json);
// "domain\\username"
        }
    }
}

对枚举的序列化

  增加枚举属性

using System;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;


namespace ConsoleApplication1
{
    internal class Program
    {
        
        public enum UserStatus
{
    NotConfirmed,
    Active,
    Deleted
}

public class User
{
    public string UserName { get; set; }

    [JsonConverter(typeof(StringEnumConverter))]
    public UserStatus Status { get; set; }
}
        private static void Main(string[] args)
        {
             User user = new User
{
    UserName = @"domain\username",
    Status = UserStatus.Deleted
};

string json = JsonConvert.SerializeObject(user, Formatting.Indented);

Console.WriteLine(json);
// {
//   "UserName": "domain\\username",
//   "Status": "Deleted"
// }
        }
    }
}

选择某些字段不序列化 

using System;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;


namespace ConsoleApplication1
{
    internal class Program
    {
        [JsonObject(MemberSerialization.OptIn)]
        public class File
        {
            // excluded from serialization
            // does not have JsonPropertyAttribute
            public Guid Id { get; set; }

            [JsonProperty]
            public int Age;

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

            [JsonProperty]
            public int Size { get; set; }
        }

        private static void Main(string[] args)
        {
            File file = new File
            {
                Id = Guid.NewGuid(),
                Age = 1,
                Name = "ImportantLegalDocuments.docx",
                Size = 50*1024
            };

            string json = JsonConvert.SerializeObject(file, Formatting.Indented);

            Console.WriteLine(json);
// {
//   "Name": "ImportantLegalDocuments.docx",
//   "Size": 51200
// }
        }
    }
}

修改属性名字

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;


namespace ConsoleApplication1
{
    internal class Program
    {

        public class Test
        {
            [JsonProperty("test1111")]
            public int Age;
        }

        private static void Main(string[] args)
        {
            Test test = new Test();

            string res = JsonConvert.SerializeObject(test);
            Console.WriteLine(res);
        }
    }
}

控制序列化顺序

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;


namespace ConsoleApplication1
{
    internal class Program
    {

        public class Test
        {
            [JsonProperty(Order=3)]
            public int Age;

            [JsonProperty(Order=2)]
            public string Name;
        }

        private static void Main(string[] args)
        {
            Test test = new Test();

            string res = JsonConvert.SerializeObject(test, Formatting.Indented);
            Console.WriteLine(res);
        }
    }
}

属性是否能为null

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;


namespace ConsoleApplication1
{
    internal class Program
    {

        public class Test
        {
            [JsonProperty(Required= Required.Default)]
            public int Age;

            [JsonProperty(Required = Required.AllowNull)]
            public string Name;
        }

        private static void Main(string[] args)
        {
            Test test = new Test();

            string res = JsonConvert.SerializeObject(test, Formatting.Indented);
            Console.WriteLine(res);
        }
    }
}

是否开启引用

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;


namespace ConsoleApplication1
{
    internal class Program
    {
        public class Business
        {
            public string Name { get; set; }

            [JsonProperty(ItemIsReference = true)]
            public IList<Employee> Employees { get; set; }
        }

        public class Employee
        {
            public string Name { get; set; }

            [JsonProperty(IsReference = true)]
            public Employee Manager { get; set; }
        }

        private static void Main(string[] args)
        {
            Employee manager = new Employee
            {
                Name = "George-Michael"
            };
            Employee worker = new Employee
            {
                Name = "Maeby",
                Manager = manager
            };

            Business business = new Business
            {
                Name = "Acme Ltd.",
                Employees = new List<Employee>
                {
                    manager,
                    worker
                }
            };

            string json = JsonConvert.SerializeObject(business, Formatting.Indented);

            Console.WriteLine(json);

        }
    }
}

 是否序列化为NULL的属性

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;


namespace ConsoleApplication1
{
    internal class Program
    {
        public class Business
        {
            [JsonProperty(NullValueHandling= NullValueHandling.Ignore)]
            public string Name { get; set; }
        }

       
        private static void Main(string[] args)
        {
          

            Business business = new Business();

            string json = JsonConvert.SerializeObject(business, Formatting.Indented);

            Console.WriteLine(json);

        }
    }
}

错误处理属性

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;


namespace ConsoleApplication1
{
    internal class Program
    {
        public class Business
        {
            private string name;

            public string Name {
                get
                {
                    if (name == null)
                    {
                        throw new Exception("zk");
                    }

                    return name;
                }
            
                set { name = value; } 
            }

            [OnError]
            internal void OnError(StreamingContext context, ErrorContext errorContext)
            {
                errorContext.Handled = true;
            }
        }

       
        private static void Main(string[] args)
        {
            Business business = new Business();

            string json = JsonConvert.SerializeObject(business, Formatting.Indented);

            Console.WriteLine(json);

        }
    }
}

DefaultValueAttribute修改属性默认值

  

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;


namespace ConsoleApplication1
{
    internal class Program
    {
        public class Business
        {
            /// <summary>
            /// 修改属性默认值为"zk"
            /// </summary>
            [DefaultValue("zk")]
            public string Name
            {
                get;
                set;
            }
        }

       
        private static void Main(string[] args)
        {
            Business business = new Business();

            string json = JsonConvert.SerializeObject(business, Formatting.Indented);

            Console.WriteLine(json);

        }
    }
}

 序列化和反序列化不同阶段调用的回调函数

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;


namespace ConsoleApplication1
{
    internal class Program
    {
        public class SerializationEventTestObject
        {
            // 2222
            // This member is serialized and deserialized with no change.
            public int Member1 { get; set; }

            // The value of this field is set and reset during and 
            // after serialization.
            public string Member2 { get; set; }

            // This field is not serialized. The OnDeserializedAttribute 
            // is used to set the member value after serialization.
            [JsonIgnore]
            public string Member3 { get; set; }

            // This field is set to null, but populated after deserialization.
            public string Member4 { get; set; }

            public SerializationEventTestObject()
            {
                Member1 = 11;
                Member2 = "Hello World!";
                Member3 = "This is a nonserialized value";
                Member4 = null;
            }

            [OnSerializing]
            internal void OnSerializingMethod(StreamingContext context)
            {
                Member2 = "This value went into the data file during serialization.";
            }

            [OnSerialized]
            internal void OnSerializedMethod(StreamingContext context)
            {
                Member2 = "This value was reset after serialization.";
            }

            [OnDeserializing]
            internal void OnDeserializingMethod(StreamingContext context)
            {
                Member3 = "This value was set during deserialization";
            }

            [OnDeserialized]
            internal void OnDeserializedMethod(StreamingContext context)
            {
                Member4 = "This value was set after deserialization.";
            }
        }


        private static void Main(string[] args)
        {
            SerializationEventTestObject obj = new SerializationEventTestObject();

            Console.WriteLine(obj.Member1);
// 11
            Console.WriteLine(obj.Member2);
// Hello World!
            Console.WriteLine(obj.Member3);
// This is a nonserialized value
            Console.WriteLine(obj.Member4);
// null

            string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
// {
//   "Member1": 11,
//   "Member2": "This value went into the data file during serialization.",
//   "Member4": null
// }

            Console.WriteLine(obj.Member1);
// 11
            Console.WriteLine(obj.Member2);
// This value was reset after serialization.
            Console.WriteLine(obj.Member3);
// This is a nonserialized value
            Console.WriteLine(obj.Member4);
// null

            obj = JsonConvert.DeserializeObject<SerializationEventTestObject>(json);

            Console.WriteLine(obj.Member1);
// 11
            Console.WriteLine(obj.Member2);
// This value went into the data file during serialization.
            Console.WriteLine(obj.Member3);
// This value was set during deserialization
            Console.WriteLine(obj.Member4);
// This value was set after deserialization.
        }
    }
}

微软的DataContract and DataMember 属性替代json的属性

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;


namespace ConsoleApplication1
{
    internal class Program
    {
        [DataContract]
        public class File
        {
            // excluded from serialization
            // does not have DataMemberAttribute
            public Guid Id { get; set; }

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

            [DataMember]
            public int Size { get; set; }
        }

        private static void Main(string[] args)
        {
            File file = new File
            {
                Id = Guid.NewGuid(),
                Name = "ImportantLegalDocuments.docx",
                Size = 50*1024
            };

            string json = JsonConvert.SerializeObject(file, Formatting.Indented);

            Console.WriteLine(json);
// {
//   "Name": "ImportantLegalDocuments.docx",
//   "Size": 51200
// }
        }
    }
}

Deserialize with dependency injection

暂无

反序列化时对额外数据的处理

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;


namespace ConsoleApplication1
{
    internal class Program
    {
        public class DirectoryAccount
        {
            // normal deserialization
            public string DisplayName { get; set; }

            // these properties are set in OnDeserialized
            public string UserName { get; set; }
            public string Domain { get; set; }

            [JsonExtensionData] private IDictionary<string, JToken> _additionalData;

            [OnDeserialized]
            private void OnDeserialized(StreamingContext context)
            {
                // SAMAccountName is not deserialized to any property
                // and so it is added to the extension data dictionary
                string samAccountName = (string) _additionalData["SAMAccountName"];

                Domain = samAccountName.Split('\\')[0];
                UserName = samAccountName.Split('\\')[1];
            }

            public DirectoryAccount()
            {
                _additionalData = new Dictionary<string, JToken>();
            }
        }

        private static void Main(string[] args)
        {
            string json = @"{
  'DisplayName': 'John Smith',
  'SAMAccountName': 'contoso\\johns'
}";

            DirectoryAccount account = JsonConvert.DeserializeObject<DirectoryAccount>(json);

            Console.WriteLine(account.DisplayName);
// John Smith

            Console.WriteLine(account.Domain);
// contoso

            Console.WriteLine(account.UserName);
// johns
        }
    }
}

 

反序列化对datetime的格式处理

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;


namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            string json = @"[
  '7 December, 2009',
  '1 January, 2010',
  '10 February, 2010'
]";

            IList<DateTime> dateList = JsonConvert.DeserializeObject<IList<DateTime>>(json, new JsonSerializerSettings
            {
                DateFormatString = "d MMMM, yyyy"
            });

            foreach (DateTime dateTime in dateList)
            {
                Console.WriteLine(dateTime.ToLongDateString());
            }
// Monday, 07 December 2009
// Friday, 01 January 2010
// Wednesday, 10 February 2010
        }
    }
}

 

序列化时对datetime格式的处理

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;


namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            IList<DateTime> dateList = new List<DateTime>
            {
                new DateTime(2009, 12, 7, 23, 10, 0, DateTimeKind.Utc),
                new DateTime(2010, 1, 1, 9, 0, 0, DateTimeKind.Utc),
                new DateTime(2010, 2, 10, 10, 0, 0, DateTimeKind.Utc)
            };

            string json = JsonConvert.SerializeObject(dateList, new JsonSerializerSettings
            {
                DateFormatString = "d MMMM, yyyy",
                Formatting = Formatting.Indented
            });

            Console.WriteLine(json);
// [
//   "7 December, 2009",
//   "1 January, 2010",
//   "10 February, 2010"
// ]
        }
    }
}

 Convert JSON to XML

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Runtime.Serialization;
using System.Xml.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;


namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            string json = @"{
  '@Id': 1,
  'Email': 'james@example.com',
  'Active': true,
  'CreatedDate': '2013-01-20T00:00:00Z',
  'Roles': [
    'User',
    'Admin'
  ],
  'Team': {
    '@Id': 2,
    'Name': 'Software Developers',
    'Description': 'Creators of fine software products and services.'
  }
}";

            XNode node = JsonConvert.DeserializeXNode(json, "root");

            Console.WriteLine(node.ToString());
// <Root Id="1">
//   <Email>james@example.com</Email>
//   <Active>true</Active>
//   <CreatedDate>2013-01-20T00:00:00Z</CreatedDate>
//   <Roles>User</Roles>
//   <Roles>Admin</Roles>
//   <Team Id="2">
//     <Name>Software Developers</Name>
//     <Description>Creators of fine software products and services.</Description>
//   </Team>
// </Root>
        }
    }
}

Convert XML to JSON

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;


namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
          string xml = @"<?xml version='1.0' standalone='no'?>
<root>
  <person id='1'>
  <name>Alan</name>
  <url>http://www.google.com</url>
  </person>
  <person id='2'>
  <name>Louis</name>
  <url>http://www.yahoo.com</url>
  </person>
</root>";

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

string json = JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.Indented);

Console.WriteLine(json);
// {
//   "?xml": {
//     "@version": "1.0",
//     "@standalone": "no"
//   },
//   "root": {
//     "person": [
//       {
//         "@id": "1",
//         "name": "Alan",
//         "url": "http://www.google.com"
//       },
//       {
//         "@id": "2",
//         "name": "Louis",
//         "url": "http://www.yahoo.com"
//       }
//     ]
//   }
// }
        }
    }
}

强制为array版本

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;


namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            string xml = @"<person id='1'>
  <name>Alan</name>
  <url>http://www.google.com</url>
  <role>Admin1</role>
</person>";

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            string json = JsonConvert.SerializeXmlNode(doc);

            Console.WriteLine(json);
// {
//   "person": {
//     "@id": "1",
//     "name": "Alan",
//     "url": "http://www.google.com",
//     "role": "Admin1"
//   }
// }

            xml = @"<person xmlns:json='http://james.newtonking.com/projects/json' id='1'>
  <name>Alan</name>
  <url>http://www.google.com</url>
  <role json:Array='true'>Admin</role>
</person>";

            doc = new XmlDocument();
            doc.LoadXml(xml);

            json = JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.Indented);

            Console.WriteLine(json);
// {
//   "person": {
//     "@id": "1",
//     "name": "Alan",
//     "url": "http://www.google.com",
//     "role": [
//       "Admin"
//     ]
//   }
// }
        }
    }
}

Read JSON with JsonTextReader

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;


namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            string json = @"{
'cpu':'intel',
'psu':'500w',
'drivers':[
'dvd',
'zk1',
'200d'
]
}";

            JsonTextReader reader = new JsonTextReader(new StringReader(json));

            while (reader.Read())
            {
                if (reader.Value != null)
                {
                    Console.WriteLine("Token: {0}, Value: {1}", reader.TokenType, reader.Value);
                }
                else
                {
                    Console.WriteLine("Token: {0}", reader.TokenType);
                }
            }
        }
    }
}

Write JSON with JsonTextWriter

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Formatting = Newtonsoft.Json.Formatting;


namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);

            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.Indented;

                writer.WriteStartObject();
                writer.WritePropertyName("CPU");
                writer.WriteValue("Intel");
                writer.WritePropertyName("PSU");
                writer.WriteValue("500W");
                writer.WritePropertyName("Drives");
                writer.WriteStartArray();
                writer.WriteValue("DVD read/writer");
                writer.WriteComment("(broken)");
                writer.WriteValue("500 gigabyte hard drive");
                writer.WriteValue("200 gigabype hard drive");
                writer.WriteEnd();
                writer.WriteEndObject();
            }

            Console.WriteLine(sb.ToString());
// {
//   "CPU": "Intel",
//   "PSU": "500W",
//   "Drives": [
//     "DVD read/writer"
//     /*(broken)*/,
//     "500 gigabyte hard drive",
//     "200 gigabype hard drive"
//   ]
// }
        }
    }
}

自定义类型转化

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Formatting = Newtonsoft.Json.Formatting;


namespace ConsoleApplication1
{
    internal class Program
    {
        public class BoolConvert : JsonConverter
        {
            private string[] arrBString
            {
                get; set;
            }

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

            public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            {
                bool bValue = (bool) value;

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

            public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
            {
                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;
                    }
                }

                throw new Exception(string.Format("Unexpected token {0} when parsing enum", reader.TokenType));
            }

            public override bool CanConvert(Type objectType)
            {
                return true;
            }
        }

        public class Person 
        {
            [JsonConverter(typeof(BoolConvert))]
            public bool isMarry
            {
                get;
                set;
            }
        }

        private static void Main(string[] args)
        {
            Person person = new Person();

            string res = JsonConvert.SerializeObject(person);
            Console.WriteLine(res);

            string json = @"{
            'isMarray':'是'
}";

             person = JsonConvert.DeserializeObject<Person>(json);

             Console.WriteLine(person.isMarry);
        }
    }
}

动态决定序列化属性

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Formatting = Newtonsoft.Json.Formatting;


namespace ConsoleApplication1
{
    internal class Program
    {
        public class LimitPropsContractResolver : DefaultContractResolver
        {
            private string[] props = null;

            private bool retain;

            /// <summary>
            /// 构造函数
            /// </summary>
            /// <param name="props">传入的属性数组</param>
            /// <param name="retain">true:表示props是需要保留的字段  false:表示props是要排除的字段</param>
            public LimitPropsContractResolver(string[] props, bool retain = true)
            {
                //指定要序列化属性的清单
                this.props = props;

                this.retain = retain;
            }

            protected override IList<JsonProperty> CreateProperties(Type type,

                MemberSerialization memberSerialization)
            {
                IList<JsonProperty> list =
                    base.CreateProperties(type, memberSerialization);
                //只保留清单有列出的属性
                return list.Where(p =>
                {
                    if (retain)
                    {
                        return props.Contains(p.PropertyName);
                    }
                    else
                    {
                        return !props.Contains(p.PropertyName);
                    }
                }).ToList();
            }

            public class Person
            {

                public bool isMarry { get; set; }

                public int Age { get; set; }
            }

            private static void Main(string[] args)
            {
                Person p = new Person();

                JsonSerializerSettings jsetting = new JsonSerializerSettings();
                jsetting.ContractResolver = new LimitPropsContractResolver(new string[] {"Age"});
                string res = JsonConvert.SerializeObject(p, Formatting.Indented, jsetting);

                Console.WriteLine(res);
            }
        }
    }
}