JSON

.Net使用Newtonsoft.Json.dll(JSON.NET)对象序列化成json、反序(3)

字号+ 作者:H5之家 来源:H5之家 2017-05-22 13:05 我要评论( )

我们发现该序列化方法抛出了异常,并没有按照我们预想的方式进行反序列化,JSON.NET提供如下的方式指定公有构造函数。 ;Website website = Newtonsoft.Json.JsonConvert.DeserializeObjectWebsite(json, new Newton

我们发现该序列化方法抛出了异常,并没有按照我们预想的方式进行反序列化,JSON.NET提供如下的方式指定公有构造函数。

; Website website = Newtonsoft.Json.JsonConvert.DeserializeObject<Website>(json, new Newtonsoft.Json.JsonSerializerSettings { ConstructorHandling = Newtonsoft.Json.ConstructorHandling.AllowNonPublicDefaultConstructor }); Console.WriteLine(website.Url);

执行结果:

另外,JSON.NET提供了指定任何构造函数的JsonConstructorAttribute特性,只需要在构造函数上标记,即可指定构造函数。

public class Users { ; } ; } public Users() { } [Newtonsoft.Json.JsonConstructor] public Users(string userName, bool enabled) { UserName = userName; Enabled = enabled; } } ; Users user = Newtonsoft.Json.JsonConvert.DeserializeObject<Users>(json); Console.WriteLine(user.UserName);

执行结果:

13、当对象的属性为默认值(0或null)时不序列化该属性

public class Person { public string Name { get; set; } public int Age { get; set; } public Person Partner { get; set; } public decimal? Salary { get; set; } } Person person1 = new Person(); string json1 = Newtonsoft.Json.JsonConvert.SerializeObject(person1, Newtonsoft.Json.Formatting.Indented, new Newtonsoft.Json.JsonSerializerSettings { DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore }); Console.WriteLine(json1); Console.WriteLine(""); Person person2 = }; string json2 = Newtonsoft.Json.JsonConvert.SerializeObject(person2, Newtonsoft.Json.Formatting.Indented, new Newtonsoft.Json.JsonSerializerSettings { DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore }); Console.WriteLine(json2);

执行结果:

14、Newtonsoft.Json(JSON.NET)中忽略null值得处理器

public class Person { public string Name { get; set; } public int Age { get; set; } public Person Partner { get; set; } public decimal? Salary { get; set; } } Person person = , Age = 46 }; string jsonIncludeNullValues = Newtonsoft.Json.JsonConvert.SerializeObject(person, Newtonsoft.Json.Formatting.Indented); Console.WriteLine(jsonIncludeNullValues); Console.WriteLine(""); string json = Newtonsoft.Json.JsonConvert.SerializeObject(person, Newtonsoft.Json.Formatting.Indented, new Newtonsoft.Json.JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore }); Console.WriteLine(json);

执行结果:

15、JSON.NET中循环引用的处理方法

Employee employee1 = }; Employee employee2 = }; employee1.Manager = employee2; employee2.Manager = employee2; string json = Newtonsoft.Json.JsonConvert.SerializeObject(employee1, Newtonsoft.Json.Formatting.Indented, new Newtonsoft.Json.JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore }); Console.WriteLine(json); public class Employee { public string Name { get; set; } public Employee Manager { get; set; } }

执行结果:

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
网友点评
d