1.缩进json
1 internal class Program 2 { 3 static void Main(string[] args) 4 { 5 var student = new Student() 6 { 7 ID = 1, 8 Age = 2, 9 Name = "abc" 10 }; 11 var json = JsonConvert.SerializeObject(student, Formatting.Indented); 12 13 Console.WriteLine(json); 14 Console.ReadLine(); 15 } 16 } 17 18 19 public class Student 20 { 21 public int ID { get; set; } 22 23 public string Name { get; set; } 24 25 public int Age { get; set; } 26 }
2.自定义配置
namespace NewtonSoft.Json.Project { using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; internal class Program { static void Main(string[] args) { var student = new Student() { ID = 1, Age = 2, Name = "abc", School = "jkllkjl" }; var employee = new Employee() { ID = 2, Age = 3, Name = "def", Company = "jmmm", Department = "dffj" }; var list = new List<Person>() { student, employee }; var setting = new JsonSerializerSettings() { // 缩进 Formatting = Formatting.Indented, ContractResolver = new DefaultContractResolver() { // 名称表示方式 NamingStrategy = new DefaultNamingStrategy() }, // 忽略null NullValueHandling = NullValueHandling.Ignore, // string 转义 StringEscapeHandling = StringEscapeHandling.Default, // 带有序列化类型(反序列化接口或抽象类) TypeNameHandling = TypeNameHandling.Auto, // 反序列化后对原始对象操作(用JsonConvert.PopulateObject) ObjectCreationHandling = ObjectCreationHandling.Auto, }; //var json = JsonConvert.SerializeObject(list, setting); var jsonStr = @" [ { ""$type"": ""NewtonSoft.Json.Project.Student, NewtonSoft.Json.Project"", ""School"": ""jkllkjl"", ""ID"": 1, ""Name"": ""abc"", ""Age"": 2 }, { ""$type"": ""NewtonSoft.Json.Project.Employee, NewtonSoft.Json.Project"", ""Company"": ""jmmm"", ""Department"": ""dffj"", ""ID"": 2, ""Name"": ""def"", ""Age"": 3 } ] "; var obj = JsonConvert.DeserializeObject<List<Person>>(jsonStr, setting); Console.WriteLine(obj); Console.ReadLine(); } } public class Student : Person { public string School { get; set; } } public class Employee : Person { public string Company { get; set; } public string Department { get; set; } } public abstract class Person { public int ID { get; set; } public string Name { get; set; } public int Age { get; set; } } }
3.特性
1 [JsonObject(MemberSerialization = MemberSerialization.OptOut)] 2 public class Employee : Person 3 { 4 /// <summary> 5 /// 作为Json属性 6 /// </summary> 7 [JsonProperty] 8 public DateTime CeateTime = DateTime.Now; 9 10 public string Company { get; set; } 11 12 public string Department { get; set; } 13 14 /// <summary> 15 /// 忽略. 16 /// </summary> 17 [JsonIgnore] 18 public string Description => $"{Name} is {Age} years old"; 19 }