关键词:
JSON作为一种轻量级的数据交换格式,简单灵活,被很多系统用来数据交互,作为一名.NET开发人员,JSON.NET无疑是最好的序列化框架,支持XML和JSON序列化,高性能,免费开源,支持LINQ查询。目前已被微软集成于webapi框架之中,因此,熟练掌握JSON.NET相当重要,这篇文章是零度参考官网整理的示例,通过这些示例,可以全面了解JSON.NET提供的功能。
Newtonsoft.Json的地址:
源码地址:https://github.com/JamesNK/Newtonsoft.Json
Newtonsoft.Json.dll下载:https://github.com/JamesNK/Newtonsoft.Json/releases
1、使用Newtonsoft.Json(JSON.NET)序列化对象,通过Newtonsoft.Json.Formatting将json格式化输出。
Account account = new Account { Email = "1930906722@qq.com", Active = true, CreatedDate =DateTime.Now, Roles = new List<string> { "User", "Admin" } }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(account, Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
public class Account { public string Name { get; set; } public string Email { get; set; } public bool Active { get; set; } public DateTime CreatedDate { get; set; } public IList<string> Roles { get; set; } }
执行结果:
2、使用Newtonsoft.Json(JSON.NET)序列化List集合:
List<string> videogames = new List<string> { "HTML5", "JavaScript", ".net","c#",".net core" }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(videogames); Console.WriteLine(json);
执行结果:
3、使用Newtonsoft.Json(JSON.NET)序列化dictionary字典
System.Collections.Generic.Dictionary<string, string> dic = new System.Collections.Generic.Dictionary<string, string> { { "Name", "张三" }, { "Age", "20" }, { "Email", "193090622@qq.com" } }; string json1 = Newtonsoft.Json.JsonConvert.SerializeObject(dic, Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json1); Console.WriteLine(""); Console.WriteLine("未格式化的json:"); string json2 = Newtonsoft.Json.JsonConvert.SerializeObject(dic, Newtonsoft.Json.Formatting.None); Console.WriteLine(json2);
执行结果:
4、Newtonsoft.Json(JSON.NET)将序列化结果保存到指定的文件:
User movie = new User { Name = "张三", Age = 1993 }; using (System.IO.StreamWriter file = System.IO.File.CreateText(@"F:\UserInfo.txt")) { Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer(); serializer.Serialize(file, movie); }
public class User { public string Name { set; get; } public int Age { set; get; } }
执行后保存到文件的结果:
5、Newtonsoft.Json(JSON.NET)基于枚举类型的JsonConverters转换器
List<JosnEnum> list = new List<JosnEnum> { JosnEnum.NotStartus, JosnEnum.Startus }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(list); Console.WriteLine(json); Console.WriteLine(""); System.Collections.Generic.Dictionary<string, int> dic = new System.Collections.Generic.Dictionary<string, int> { {((JosnEnum)(int)JosnEnum.NotStartus).ToString() ,(int)JosnEnum.NotStartus} , {((JosnEnum)(int)JosnEnum.Startus).ToString() ,(int)JosnEnum.Startus} }; string dicJson = Newtonsoft.Json.JsonConvert.SerializeObject(dic); Console.WriteLine(dicJson); Console.WriteLine(""); List<JosnEnum> list2 = new List<JosnEnum> { JosnEnum.NotStartus, JosnEnum.Startus }; string json3 = Newtonsoft.Json.JsonConvert.SerializeObject(list2, new Newtonsoft.Json.Converters.StringEnumConverter()); Console.WriteLine(json3); Console.WriteLine(""); List<JosnEnum> result = Newtonsoft.Json.JsonConvert.DeserializeObject<List<JosnEnum>>(json3, new Newtonsoft.Json.Converters.StringEnumConverter()); Console.WriteLine(string.Join(", ", result.Select(c => c.ToString())));
public enum JosnEnum { NotStartus = 0, Startus = 1 }
执行结果:
6、Newtonsoft.Json(JSON.NET)通过JRaw将JS函数序列化到JSON中
JavaScriptSettings settings = new JavaScriptSettings { OnLoadFunction = new Newtonsoft.Json.Linq.JRaw("OnLoad"), OnSucceedFunction = new Newtonsoft.Json.Linq.JRaw("function(e) { alert(e); }") }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(settings, Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
public class JavaScriptSettings { public Newtonsoft.Json.Linq.JRaw OnLoadFunction { get; set; } public Newtonsoft.Json.Linq.JRaw OnSucceedFunction { get; set; } }
7、使用Newtonsoft.Json(JSON.NET)将json反序列化对象
string json = @"{ 'Email': '1930906722@qq.com', 'Active': true, 'CreatedDate': '2016-11-26 20:39', 'Roles': [ 'User', 'Admin' ] }"; Account account = Newtonsoft.Json.JsonConvert.DeserializeObject<Account>(json); Console.WriteLine(account.Email);
public class Account { public string Name { get; set; } public string Email { get; set; } public bool Active { get; set; } public DateTime CreatedDate { get; set; } public IList<string> Roles { get; set; } }
执行结果:
8、使用Newtonsoft.Json(JSON.NET)反序列化List集合:
string json = @"['Html5','C#','.Net','.Net Core']"; List<string> videogames = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(json); Console.WriteLine(string.Join(", ", videogames));
执行结果:
9、使用Newtonsoft.Json(JSON.NET)反序列化dictionary字典
string json = @"{'Name': '张三','Age': '23'}"; var htmlAttributes = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(json); Console.WriteLine(htmlAttributes["Name"]); Console.WriteLine(htmlAttributes["Age"]);
执行结果:
10、使用Newtonsoft.Json(JSON.NET)序列化var匿名类型,有时候,我们并不需要先定义一个类,然后new一个对象后再进行序列化,JSON.NET支持匿名类型的序列化和反序列化。
var test1 = new { Name = "李四", Age = 26 }; var json = Newtonsoft.Json.JsonConvert.SerializeObject(test1); Console.WriteLine(json); Console.WriteLine(""); var test2 = new { Name = "", Age = 0 }; string json1 = @"{'Name':'张三','Age':'25'}"; var result = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(json1, test2); Console.WriteLine(result.Name);
执行结果:
11、Newtonsoft.Json(JSON.NET)用新JSON字符串填充指定对象的属性值
Account account = new Account { Email = "1930906722@qq.com", Active = true, CreatedDate = DateTime.Now, Roles = new List<string> { "User", "Admin" } }; string json = @"{'Active': false, 'Roles': ['Expired']}"; Newtonsoft.Json.JsonConvert.PopulateObject(json, account); Console.WriteLine(account.Active); Console.WriteLine(account.Email);
public class Account { public string Name { get; set; } public string Email { get; set; } public bool Active { get; set; } public DateTime CreatedDate { get; set; } public IList<string> Roles { get; set; } }
执行结果:
12、使用Newtonsoft.Json(JSON.NET)反序列化时可指定构造函数:
首先我们定义如下的类型,我们希望JSON.NET反序列化对象时使用第2个构造函数,我们将第一个默认构造函数屏蔽,标记为私有private修饰符。第2个构造函数需要指定一个website对象作为参数,如果提供的参数为null则抛出异常:
public class Website { public string Url { get; set; } private Website() { } public Website(Website website) { if (website == null) throw new ArgumentNullException("website"); Url = website.Url; } }
现在使用一般的方式反序列化一个JSON字符串。执行出现的结果:
我们发现该序列化方法抛出了异常,并没有按照我们预想的方式进行反序列化,JSON.NET提供如下的方式指定公有构造函数。
string json = @"{'Url':'http://www.cnblogs.com/linJie1930906722/'}"; 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 string UserName { get; private set; } public bool Enabled { get; private set; } public Users() { } [Newtonsoft.Json.JsonConstructor] public Users(string userName, bool enabled) { UserName = userName; Enabled = enabled; } }
string json = @"{""UserName"": ""希特勒"",""Enabled"": true}"; 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 = new Person(){Name = "奥巴马"}; 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 = new Person { Name = "张三", 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 = new Employee { Name = "张三" }; Employee employee2 = new Employee { Name = "李四" }; 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; } }
执行结果:
16、通过ContractResolver指定属性名首字母小写,通常,在.NET中属性采用PascalCase规则(首字母大写),在JavaScript中属性名使用CamelCase规则(首字母小写),我们希望序列化后的JSON字符串符合CamelCase规则,JSON.NET提供的ContractResolver可以设置属性名小写序列化
public class User { public string Name { set; get; } public int Age { set; get; } }
User person = new User { Name = "张三", Age =52 }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(person, Newtonsoft.Json.Formatting.Indented, new Newtonsoft.Json.JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }); Console.WriteLine(json);
执行结果:
17、JSON.NET中通过特性序列化枚举类型
public enum ProductStatus { NotConfirmed, Active, Deleted } public class Product { public string Name { get; set; } [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] public ProductStatus Status { get; set; } }
Product user = new Product { Name = @"羽绒服", Status = ProductStatus.Deleted }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(user, Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
执行结果:
18、指定需要序列化的属性
[Newtonsoft.Json.JsonObject(Newtonsoft.Json.MemberSerialization.OptIn)] public class Categroy { //Id不需要序列化 public Guid Id { get; set; } [Newtonsoft.Json.JsonProperty] public string Name { get; set; } [Newtonsoft.Json.JsonProperty] public int Size { get; set; } }
Categroy categroy = new Categroy { Id = Guid.NewGuid(), Name = "内衣", Size = 52 }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(categroy, Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
执行结果:
19、序列化对象时指定属性名
public class Videogame { [Newtonsoft.Json.JsonProperty("name")] public string Name { get; set; } [Newtonsoft.Json.JsonProperty("release_date")] public DateTime ReleaseDate { get; set; } }
Videogame starcraft = new Videogame { Name = "英雄联盟", ReleaseDate = DateTime.Now }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(starcraft, Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
执行结果:
20、序列化时指定属性在JSON中的顺序
public class Personl { [Newtonsoft.Json.JsonProperty(Order = 2)] public string FirstName { get; set; } [Newtonsoft.Json.JsonProperty(Order = 1)] public string LastName { get; set; } }
Personl person = new Personl { FirstName = "张三", LastName = "李四" }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(person, Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
执行结果:
21、反序列化指定属性是否必须有值必须不为null,在反序列化一个JSON时,可通过JsonProperty特性的Required指定反序列化行为,当反序列化行为与指定的行为不匹配时,JSON.NET将抛出异常,Required是枚举,Required.Always表示属性必须有值切不能为null,Required.AllowNull表示属性必须有值,但允许为null值。
public class Order { [Newtonsoft.Json.JsonProperty(Required = Newtonsoft.Json.Required.Always)] public string Name { get; set; } [Newtonsoft.Json.JsonProperty(Required = Newtonsoft.Json.Required.AllowNull)] public DateTime? ReleaseDate { get; set; } }
string json = @"{ 'Name': '促销订单', 'ReleaseDate': null }"; Order order = Newtonsoft.Json.JsonConvert.DeserializeObject<Order>(json); Console.WriteLine(order.Name); Console.WriteLine(order.ReleaseDate);
执行结果:
22、通过特性指定null值忽略序列化
public class Vessel { public string Name { get; set; } [Newtonsoft.Json.JsonProperty(NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public DateTime? LaunchDate { get; set; } }
Vessel vessel = new Vessel { Name = "张三" }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(vessel, Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
执行结果:
23、忽略不需要序列化的属性,并不是对象所有属性都要参与序列化,我们可以使用JsonIgnore特性排除不需要序列化的属性,下面示例中的PasswordHash将被忽略。
public class Accounts { public string FullName { get; set; } public string EmailAddress { get; set; } [Newtonsoft.Json.JsonIgnore] public string PasswordHash { get; set; } }
Accounts account = new Accounts { FullName = "admin", EmailAddress = "1930906722@qq.com", PasswordHash = "dfsfgerhtyhsasdhjyujtgwe454811sfsg8d" }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(account); Console.WriteLine(json);
执行结果:
24、序列化或反序列化时指定日期时间格式,JSON.NET中提供一个名为JsonSerializerSettings的设置对象,可通过此对象设置很多序列化和反序列化的行为,如果要设置JSON.NET序列化输出的日期时间格式,只需要指定格式化字符串即可。通过JsonSerializerSettings的DateFormatString属性指定日期时间格式:
public class Customer { public string FirstName { get; set; } public string LastName { get; set; } public DateTime CreateDate { get; set; } }
Customer custom = new Customer { FirstName = "张三", LastName = "李四", CreateDate = DateTime.Now }; Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatString = "yyyy-MM-dd HH:mm:ss", Formatting = Newtonsoft.Json.Formatting.Indented }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(custom, settings); Console.WriteLine(json);
执行结果:
使用newtonsoft.json.dll(json.net)动态解析json.net的json的序列化与反序列化
在开发中,我非常喜欢动态语言和匿名对象带来的方便,JSON.NET具有动态序列化和反序列化任意JSON内容的能力,不必将它映射到具体的强类型对象,它可以处理不确定的类型(集合、字典、动态对象和匿名对象),在这篇文章中... 查看详情
“Newtonsoft.Json.JsonConvert”类型存在于“Newtonsoft.Json.dll”和“NuGetApi2.dll”中
】“Newtonsoft.Json.JsonConvert”类型存在于“Newtonsoft.Json.dll”和“NuGetApi2.dll”中【英文标题】:Thetype\'Newtonsoft.Json.JsonConvert\'existsinboth\'Newtonsoft.Json.dll\'and\'NuGetApi2.dll\'【发布时间】:2017-01-1316:42:49【问题描述】:我正在尝试使用将... 查看详情
fineui中newtonsoft.json版本报错解决办法
1.清空bin下的Newtonsoft.Json.dll2.使用Nuget安装最新版本的Newtonsoft.Json.dll,安装脚本为 Install-Package Newtonsoft.Json3.如还报错手动将Newtonsoft.Json.dll放入bin下,手动引用Newtonsoft.Json.dll,重新生成解决方案 查看详情
从构建服务器中的错误位置复制 Newtonsoft.Json.dll
】从构建服务器中的错误位置复制Newtonsoft.Json.dll【英文标题】:Newtonsoft.Json.dllbeingcopiedfromwronglocationinthebuildserver【发布时间】:2015-10-1615:06:30【问题描述】:我在这里遇到了一些奇怪的问题,有一个在VisualStudio中正常构建的软... 查看详情
c#unity(发布到安卓端中使用)解析json字符串—使用微软官方的包newtonsoft.json(代码片段)
...c;所以记录下如何在安卓端使用并解析json;使用工具:Newtonsoft.Json,是.Net中开源的Json序列化和反序列化工具,官方地址:http://www.newtonsoft.com/json。Newtonsoft.Json文档:https://www.newtonsoft.com/json/help/html/Overload_Newtonso... 查看详情
c#unity(发布到安卓端中使用)解析json字符串—使用微软官方的包newtonsoft.json(代码片段)
...c;所以记录下如何在安卓端使用并解析json;使用工具:Newtonsoft.Json,是.Net中开源的Json序列化和反序列化工具,官方地址:http://www.newtonsoft.com/json。Newtonsoft.Json文档:https://www.newtonsoft.com/json/help/html/Overload_Newtonso... 查看详情
asp.netc#使用newtonsoft.json实现datatable转json格式数据
引用Newtonsoft.Json.dll 下载地址:http://www.newtonsoft.com/products/json/ //在项目中添加引用//引用命名空间usingNewtonsoft.Json;usingNewtonsoft.Json.Converters;//DataTable转换成jsonpublicstringGetAllCategory(){stri 查看详情
newtonsoft.json.dll读取json格式字符串值
usingNewtonsoft.Json;usingNewtonsoft.Json.Linq;stringjsonText="[{‘a‘:‘aaa‘,‘b‘:‘bbb‘,‘c‘:‘ccc‘},{‘a‘:‘aaa2‘,‘b‘:‘bbb2‘,‘c‘:‘ccc2‘}]";stringa=JObject.Parse(JArray.Parse(jsonText)[0].ToString())["a"].To 查看详情
newtonsoft.json.dll反序列化json字符串
上一篇JSON博客《JSON入门级学习小结--JSON数据结构》中已对JSON做了简单介绍,JSON字符串数组数据样式大概是这样子的: 如今因为项目需求(asp.netweb网站,前台向后台传递JSON数据,并... 查看详情
无法访问动态属性
...。为了便于阅读,我修改了下面的代码。我正在使用包:Newtonsoft.Json.8.0.1\\lib\\net45\\Newtonsoft.Json.dll我正在尝试在下面的代码中读取对象mDevice:代码foreach(dynami 查看详情
c#newtonsoft.json.dlljson数据格式上传下载解析(代码片段)
前提需要导入Newtonsoft.Json.dll 1.创建实体输入json参数对象[JsonObject(MemberSerialization.OptOut)]classGateSignInputInfo///<summary>///考场代号///</summary>publicstringkcdhget;set;=string.Empty;///< 查看详情
c#怎么获取json的数据循环到对象里
...库可以使用了,.net有自带,也可以使用第三方的,如,Newtonsoft.Json.dll,比较方便,而且可以直接转换为实体,也可以把实体转换为json,非常方便的。 参考技术Bvarmodel=JObject.Parse(paramStr).ToObject<你的类名>(); 查看详情
如何将这个json进行解析?
...析(如果是php有一个json_decode()就行);如果是C#,找一个Newtonsoft.JSON.dll,或者用.NET3.5自带的方式。Newtonsoft好像有其他语言的版本!也可以通过正则表达式提取你需要的内容。总之方式比较多,按照你的业务来! 参考技术BNewtonsof... 查看详情
解决未能加载文件或程序集“newtonsoft.json...."或它的某一个依赖项。找到的程序集清单定义与程序集引用不匹配。(异常来自hresult:0x80131040)(代码片段
...。因为需要引用一个第三方的类库,三方的类库引用的是Newtonsoft.Json.dll版本7.0.0而我的项目中引用的是Newtonsoft.Json.dll版本4.5.0,这样两个引用造成了冲突。所有的引用都OK,编译时提示“ Newtonsoft.Json.Linq”未引用,可是这明... 查看详情
vs:webapi调试发生filenotfoundexception异常
...开C:\\Program Files (x86)\\Microsoft Web Tools\\DNU\\Newtonsoft.Json\\6.0.6\\lib打开自己版本的net版本的文件夹下的Newtonsoft.Json.dll添加。追问感谢,感谢,再次感谢.本回答被提问者采纳 查看详情
如何将c#/.net将json字符串格式数据转换成对象?
参考技术A下个Newtonsoft.Json插件引用Newtonsoft.Json.dll1、json字符串stringxxx="\"count\":\"1\",\"Product_Code\":\"14003949\",\"Product_Name\":\"聚丙烯树脂\",\"... 查看详情
dll版本冲突问题(代码片段)
...icrosoft-com:asm.v1"><dependentAssembly><assemblyIdentityname="Newtonsoft.Json"publicKeyToken="30ad4fe6b2a6aeed"/><codeBaseversion="4.0.3.0"href="C:v2.0Newtonsoft.Json.dll"/><codeBaseversion="7.0.0.0"href="C:v3.5Newtonsoft.Json.dll"/></dependentAssembly></assembly... 查看详情
NuGet 参考在开发中有效,在生产中失败
...描述】:我正在使用PushSharp传递移动推送消息,它依赖于Newtonsoft.Json.dll。我也通过NuGet安装了Newtonsoft.Json.dll,因为我也将它用于其他用途。几天前,我通过VS2012中的NuGet将Newto 查看详情