引言

有个朋友问了一个如何更方便的解析json格式字符串,之前也没怎么研究过json.net,就上网帮他查了一下,现学现卖的给他整了一个demo,这才发现json.net的强大,用着很方便。

Json

JSON(javasrcipt Object Notation)是一种轻量级的数据交换方式。拿最常见的应用举个例子,将javascript对象中表示的一组数据转换为字符串,然后就可以在函数之间轻松的传递这个字符串,或者在异步应用程序中将字符串从web客户机传递给服务端程序。这个字符串虽然看起来比较古怪,但是javascript很容易解释它,而且json可以表示比“名称/值对”更复杂的结构。例如,可以表示数组和复杂的对象,而不仅仅是键和值的简单列表。

在.net中,DataContractJsonSerializer和JavaScriptSerializer这两个类,可以操作json。但性能上和json.net相比,差了很多。

可以借用官网的一张图看一下:

[Json.net]快速入门-LMLPHP

官网地址:http://james.newtonking.com/json

将下载的压缩文件解压,Source是源码文件夹,在bin目录下,Newtonsoft.Json.dll是编译后的程序集文件,在项目中应用该dll就行了。

Json.net

在项目中引用Newtonsoft.Json.dll。

首先从最简单的例子入手,序列化DataTable对象。

引入命名空间:

using Newtonsoft.Json;

测试代码:

 using Newtonsoft.Json;
using System.Data;
namespace Wolfy.JsonNetDemo
{
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
DataColumn name = new DataColumn("Name");
DataColumn gender = new DataColumn("Gender");
DataColumn address = new DataColumn("Address");
dt.Columns.Add(name);
dt.Columns.Add(gender);
dt.Columns.Add(address);
for (int i = ; i < ; i++)
{
DataRow dr = dt.NewRow();
dr[] = "Name" + i;
dr[] = i%==?"男":"女";
dr[] = "Address" + i;
dt.Rows.Add(dr);
}
//序列化为json
string json = JsonConvert.SerializeObject(dt);
Console.WriteLine(json);
Console.Read();
}
}
}

结果:

[Json.net]快速入门-LMLPHP

反序列化为Datatable

  DataTable dt1 = JsonConvert.DeserializeObject<DataTable>(json);
for (int i = ; i < dt1.Rows.Count; i++)
{
DataRow dr = dt1.Rows[i];
Console.WriteLine("{0}\t{1}\t{2}\t", dr[], dr[], dr[]);
}

[Json.net]快速入门-LMLPHP

控制

实现对Json.net序列化和反序列化的控制,需要JsonSerializerSettings类。

var jsonSetting = new JsonSerializerSettings(); string json=JsonConvert.SerializeObject(object,jsonSetting);

新建一个测试类:

     public class Employee
{
public string Name { get; set; }
public int Age { set; get; }
public string Gender { set; get; }
public string DepartmentName { set; get; }
public Employee Leader { set; get; }
}

空值处理

针对应用类型,如果为NULL时,json.net如何处理,可以通过 jsonSetting.NullValueHandling的值来控制。如:

             var jsonSetting = new JsonSerializerSettings();
jsonSetting.NullValueHandling = NullValueHandling.Ignore;
jsonSetting.NullValueHandling = NullValueHandling.Include;

一个例子:

             Employee employee = new Employee();
employee.Name = "Wolfy";
employee.Gender = "男";
employee.Age = ;
employee.DepartmentName = ".net开发";
employee.Leader = null;
var jsonSetting = new JsonSerializerSettings();
jsonSetting.NullValueHandling = NullValueHandling.Ignore;
string json = JsonConvert.SerializeObject(employee,jsonSetting);
Console.WriteLine(json);
Console.Read();

结果:

[Json.net]快速入门-LMLPHP

改为NullValueHandling.Include

结果:

[Json.net]快速入门-LMLPHP

默认值处理

对于值类型的处理,通过设置jsonSetting.DefaultValueHandling的值来确定。同样是枚举可取Ignore,Include等,如:

 namespace Newtonsoft.Json
{
[Flags]
public enum DefaultValueHandling
{
Include = ,
Ignore = ,
Populate = ,
IgnoreAndPopulate = ,
}
}

jsonSetting.DefaultValueHandling = DefaultValueHandling.Ignore;//忽略默认值

给Employee的成员使用特性   [DefaultValue(26)]设置默认值,并引入命名空间:System.ComponentModel

[DefaultValue()] public int Age { set; get; }

忽略默认值:

             Employee employee = new Employee();
employee.Name = "Wolfy";
employee.Gender = "男";
employee.Age = ;
employee.DepartmentName = ".net开发";
employee.Leader = null;
var jsonSetting = new JsonSerializerSettings();
jsonSetting.NullValueHandling = NullValueHandling.Include;
jsonSetting.DefaultValueHandling = DefaultValueHandling.Ignore;//忽略默认值
string json = JsonConvert.SerializeObject(employee,jsonSetting);
Console.WriteLine(json);
Console.Read();

结果:

[Json.net]快速入门-LMLPHP

属性控制

Json.net序列化的两种方式:OptOut和OptIn

OptOut默认值,类中所有公共成员会被序列化,如果不想被序列化,可以使用特性JsonIgnore

OptIn默认情况下,所有的成员不会被序列化,类中的成员只有标有特性JsonProperty的才会被序列化,当类的成员很多,但客户端仅仅需要一部分时很有帮助。

 using Newtonsoft.Json;
namespace Wolfy.JsonNetDemo
{
[JsonObject(Newtonsoft.Json.MemberSerialization.OptIn)]
public class Employee
{
[JsonProperty]
public string Name { get; set; } public int Age { set; get; }
public string Gender { set; get; }
public string DepartmentName { set; get; }
public Employee Leader { set; get; }
}
}

序列化:

             Employee employee = new Employee();
employee.Name = "Wolfy";
employee.Gender = "男";
employee.Age = ;
employee.DepartmentName = ".net开发";
employee.Leader = null;
string json = JsonConvert.SerializeObject(employee);
Console.WriteLine(json);

结果:

[Json.net]快速入门-LMLPHP

如果想忽略某个属性,比如忽略领导信息。则可以这样写:

 namespace Wolfy.JsonNetDemo
{
[JsonObject(Newtonsoft.Json.MemberSerialization.OptOut)]
public class Employee
{
public string Name { get; set; } public int Age { set; get; }
public string Gender { set; get; }
public string DepartmentName { set; get; }
[JsonIgnore]
public Employee Leader { set; get; }
}
}

[JsonObject(Newtonsoft.Json.MemberSerialization.OptOut)]可以不写,已经默认

测试:

             Employee employee = new Employee();
employee.Name = "Wolfy";
employee.Gender = "男";
employee.Age = ;
employee.DepartmentName = ".net开发";
employee.Leader = new Employee() {Name = "老大",Gender = "男",Age = , DepartmentName = ".net开发"};
string json = JsonConvert.SerializeObject(employee);
Console.WriteLine(json);

结果:

[Json.net]快速入门-LMLPHP

不忽略结果对比:

[Json.net]快速入门-LMLPHP

非公共成员序列化

Json.net序列化对象,默认只序列化公共成员,非公共成员序列互时,需加上 [JsonProperty]特性。

日期处理

两种日期格式:IsoDateTimeConverter和JavaScriptDateTimeConverter

这是json.net中带的2个日期类,默认是IsoDateTimeConverter,格式“yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK”。另一个是JavaScriptDateTimeConverter,格式“new Date(ticks)”,返回Javascript的Date对象。

一个例子

     public class Employee
{
public string Name { get; set; }
public int Age { set; get; }
public string Gender { set; get; }
public string DepartmentName { set; get; }
//[JsonIgnore]
public Employee Leader { set; get; }
public DateTime BirthDay { set; get; }
public DateTime EmployeDate { set; get; }
}

序列化为Javascript格式:

             Employee employee = new Employee();
employee.Name = "Wolfy";
employee.Gender = "男";
employee.Age = ;
employee.DepartmentName = ".net开发";
employee.Leader = new Employee() {Name = "老大",Gender = "男",Age = , DepartmentName = ".net开发"};
employee.BirthDay = new DateTime(,,);
employee.EmployeDate = new DateTime(,,);
string json = JsonConvert.SerializeObject(employee,new JavaScriptDateTimeConverter());
Console.WriteLine(json);

序列化

[Json.net]快速入门-LMLPHP

如果想要不同的日期类型成员序列化后,以不同的形式显示。

则可以通过设置特性实现

     public class Employee
{
public string Name { get; set; }
public int Age { set; get; }
public string Gender { set; get; }
public string DepartmentName { set; get; }
//[JsonIgnore]
public Employee Leader { set; get; }
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime BirthDay { set; get; }
[JsonConverter(typeof(JavaScriptDateTimeConverter))]
public DateTime EmployeDate { set; get; }
}

结果:

[Json.net]快速入门-LMLPHP

自定义日期格式:

             IsoDateTimeConverter newFormatTime = new IsoDateTimeConverter() { DateTimeFormat="yyyy年MM月dd日"};
string json = JsonConvert.SerializeObject(employee, newFormatTime);
Console.WriteLine(json);

结果:

[Json.net]快速入门-LMLPHP

总结

json.net简单操作就介绍到这里,之后总结Linq to json的用法。

参考

http://james.newtonking.com/json

http://www.360doc.com/content/13/0328/22/11741424_274568478.shtml

04-28 14:12