我们知道在NET中我们有多种对象序列化的方式,如XML方式序列化、Binary序列化,其中XML序列化是一种比较通用的在各语言之间传递数据的方式。除了这两种序列化方式之外,在NET中还可以使用JSON序列化。
JSON(JavaScript Object Notation)是一种轻量级轻量级的数据交换格式,并且它独立于编程语言,与XML序列化相比,JSON序列化后产生的数据一般要比XML序列化后数据体积小,所以在Facebook等知名网站中都采用了JSON作为数据交换方式。在NET中有三种常用的JSON序列化的类,分别是 SystemWebScriptSerializationJavaScriptSerializer类、SystemRuntimeSerializationJsonDataContractJsonSerializer类和NewtonsoftJsonJsonConvert类。
为了便于下面的演示,下面提供一个类的代码:
复制代码 代码如下:
[DataContract]
publicclass User
{
///<summary>
/// 编号
///</summary>
[DataMember]
publicint UserId { get; set; }
///<summary>
/// 用户名
///</summary>
[DataMember]
publicstring UserName { get; set; }
///<summary>
/// 创建时间
///</summary>
[DataMember]
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime CreateDate { get; set; }
///<summary>
/// 生日
///</summary>
[DataMember]
[JsonConverter(typeof(JavaScriptDateTimeConverter))]
public DateTime Birthday { get; set; }
///<summary>
/// 相关URL
///</summary>
[DataMember]
public List<string> Urls { get; set; }
///<summary>
/// 薪水
///</summary>
//[ScriptIgnore]//使用JavaScriptSerializer序列化时不序列化此字段
//[IgnoreDataMember]//使用DataContractJsonSerializer序列化时不序列化此字段
//[JsonIgnore]//使用JsonConvert序列化时不序列化此字段
publicint Salary { get; set; }
///<summary>
/// 权利级别
///</summary>
[DataMember]
public Priority Priority { get; set; }
public User()
{
Urls =new List<string>();
}
}
///<summary>
/// 权利级别
///</summary>
publicenum Priority:byte
{
Lowest=0x1,
BelowNormal=0x2,
Normal=0x4,
AboveNormal=0x8,
Highest=0x16
}
使用SystemWebScriptSerializationJavaScriptSerializer类
SystemWebScriptSerializationJavaScriptSerializer类是NET类库中自带的一种JSON序列化实现,在NET Framework5及以后版本中可以使用这个类,这个类位于SystemWebExtensionsdll中,使用这个类是必须添加对这个dll的引用。
下面的代码是使用JavaScriptSerializer进行序列化和反序列化的例子:
复制代码 代码如下:
publicstaticvoid JavaScriptSerializerDemo()
{
User user =new User { UserId =1, UserName ="李刚", CreateDate = DateTimeNowAddYears(-30),Birthday=DateTimeNowAddYears(-50), Priority = PriorityHighest, Salary =500000 };
//JavaScriptSerializer类在SystemWebExtensionsdll中,注意添加这个引用
JavaScriptSerializer serializer =new JavaScriptSerializer();
//JSON序列化
string result=serializerSerialize(user);
ConsoleWriteLine("使用JavaScriptSerializer序列化后的结果:{0},长度:{1}", result, resultLength);
//JSON反序列化
user = serializerDeserialize<User>(result);
ConsoleWriteLine("使用JavaScriptSerializer反序列化后的结果:UserId:{0},UserName: {1},CreateDate:{2},Priority:{3}", userUserId, userUserName, userCreateDate, userPriority);
}
说明:如果不想序列化某个字段,可以在字段前面加[JsonIgnore]标记。
使用SystemRuntimeSerializationJsonDataContractJsonSerializer类
SystemRuntimeSerializationJsonDataContractJsonSerializer类位于SystemServiceModelWebdll中,使用这个类时除了需要添加对SystemServiceModelWebdll的引用之外,还需要添加SystemRuntimeSerializationdll的引用,注意这个类也是在NET Framework5及以后版本中可以使用。
下面是使用DataContractJsonSerializer类的例子:
复制代码 代码如下:
publicstaticvoid DataContractJsonSerializerDemo()
{
User user =new User { UserId =1, UserName ="李刚", CreateDate = DateTimeNowAddYears(-30), Birthday = DateTimeNowAddYears(-50), Priority = PriorityAboveNormal, Salary =50000 };
string result =stringEmpty;
//DataContractJsonSerializer类在SystemServiceModelWebdll中,注意添加这个引用
DataContractJsonSerializer serializer =new DataContractJsonSerializer(typeof(User));
using (MemoryStream stream =new MemoryStream())
{
//JSON序列化
serializerWriteObject(stream, user);
result = EncodingUTFGetString(streamToArray());
ConsoleWriteLine("使用DataContractJsonSerializer序列化后的结果:{0},长度:{1}", result, resultLength);
}
//JSON反序列化
byte[] buffer = EncodingUTFGetBytes(result);
using (MemoryStream stream =new MemoryStream(buffer))
{
user = serializerReadObject(stream) as User;
ConsoleWriteLine("使用DataContractJsonSerializer反序列化后的结果:UserId: {0},UserName:{1},CreateDate:{2},Priority:{3}", userUserId, userUserName, userCreateDate, userPriority);
}
}
注意:要使用DataContractJsonSerializer类进行序列化和反序列化,必须给类加上[DataContract]属性,对要序列化的字段加上[DataMember]属性,如果不想序列化某个字段或者属性,可以加上[IgnoreDataMember]属性。
使用NewtonsoftJsonJsonConvert类
NewtonsoftJsonJsonConvert类是非微软提供的一个JSON序列化和反序列的开源免费的类库(下载网址是:http://wwwcodeplexcom/json/),它提供了更灵活的序列化和反序列化控制,并且如果你的开发环境使用的是NET Framework5及以后版本的话,你就可以使用Linq to JSON,这样一来面对一大段的数据不必一一解析,你可以使用Linq to JSON解析出你关心的那部分即可,非常方便。
下面是使用NewtonsoftJsonJsonConvert类的例子:
复制代码 代码如下:
publicstaticvoid JsonConvertDemo()
{
User user =new User { UserId =1, UserName ="李刚", CreateDate = DateTimeNowAddYears(-30), Birthday = DateTimeNowAddYears(-50), Priority = PriorityBelowNormal, Salary =5000 };
//JsonConvert类在NewtonsoftJsonNetdll中,注意到http://wwwcodeplexcom/json/下载这个dll并添加这个引用
//JSON序列化
string result = JsonConvertSerializeObject(user);
ConsoleWriteLine("使用JsonConvert序列化后的结果:{0},长度:{1}", result, resultLength);
//JSON反序列化
user = JsonConvertDeserializeObject<User>(result);
ConsoleWriteLine("使用JsonConvert反序列化后的结果:UserId:{0},UserName: {1},CreateDate:{2},Priority:{3}", userUserId, userUserName, userCreateDate, userPriority);
}
publicstaticvoid JsonConvertLinqDemo()
{
User user =new User { UserId =1, UserName ="周公", CreateDate = DateTimeNowAddYears(-8), Birthday = DateTimeNowAddYears(-32), Priority = PriorityLowest, Salary =500, Urls =new List<string> { "http://zhoufoxcnblog51ctocom", "https://www.jb51.net" } };
//JsonConvert类在NewtonsoftJsonNetdll中,注意到http://wwwcodeplexcom/json/下载这个dll并添加这个引用
//JSON序列化
string result = JsonConvertSerializeObject(user);
ConsoleWriteLine("使用JsonConvert序列化后的结果:{0},长度:{1}", result, resultLength);
//使用Linq to JSON
JObject jobject = JObjectParse(result);
JToken token = jobject["Urls"];
List<string> urlList =new List<string>();
foreach (JToken t in token)
{
urlListAdd(tToString());
}
ConsoleWrite("使用Linq to JSON反序列化后的结果:[");
for (int i =0; i < urlListCount -1;i++ )
{
ConsoleWrite(urlList[i] +",");
}
ConsoleWriteLine(urlList[urlListCount -1] +"]");
}
注意:如果有不需要序列化的字段,可以给该字段添加[JsonIgnore]标记。在Newtonsoft这个类库中对于日期的序列化有多种方式,可以类的DataTime成员添加上对应的标记,这样在进行序列化和反序列化时就会按照指定的方式进行,在本例中User类的CreateDate属性添加的属性是[JsonConverter(typeof(IsoDateTimeConverter))],而Birthday属性添加的属性是[JsonConverter(typeof(JavaScriptDateTimeConverter))],从序列化的结果可以看出来它们最终的表现形式并不一样。
本文中所有的示例代码如下:
复制代码 代码如下:
using System;
using SystemCollectionsGeneric;
using SystemLinq;
using SystemText;
using SystemWebScriptSerialization;
using SystemRuntimeSerializationJson;
using SystemIO;
using SystemRuntimeSerialization;
using NewtonsoftJson;
using NewtonsoftJsonLinq;
using NewtonsoftJsonConverters;
namespace JSONDemo
{
class Program
{
staticvoid Main(string[] args)
{
JavaScriptSerializerDemo();
DataContractJsonSerializerDemo();
JsonConvertDemo();
JsonConvertLinqDemo();
ConsoleReadLine();
}
publicstaticvoid JavaScriptSerializerDemo()
{
User user =new User { UserId =1, UserName ="李刚", CreateDate = DateTimeNowAddYears(-30),Birthday=DateTimeNowAddYears(-50), Priority = PriorityHighest, Salary =500000 };
//JavaScriptSerializer类在SystemWebExtensionsdll中,注意添加这个引用
JavaScriptSerializer serializer =new JavaScriptSerializer();
//JSON序列化
string result=serializerSerialize(user);
ConsoleWriteLine("使用JavaScriptSerializer序列化后的结果:{0},长度:{1}", result, resultLength);
//JSON反序列化
user = serializerDeserialize<User>(result);
ConsoleWriteLine("使用JavaScriptSerializer反序列化后的结果:UserId:{0},UserName:{1},CreateDate:{2},Priority:{3}", userUserId, userUserName, userCreateDate, userPriority);
}
publicstaticvoid DataContractJsonSerializerDemo()
{
User user =new User { UserId =1, UserName ="李刚", CreateDate = DateTimeNowAddYears(-30), Birthday = DateTimeNowAddYears(-50), Priority = PriorityAboveNormal, Salary =50000 };
string result =stringEmpty;
//DataContractJsonSerializer类在SystemServiceModelWebdll中,注意添加这个引用
DataContractJsonSerializer serializer =new DataContractJsonSerializer(typeof(User));
using (MemoryStream stream =new MemoryStream())
{
//JSON序列化
serializerWriteObject(stream, user);
result = EncodingUTFGetString(streamToArray());
ConsoleWriteLine("使用DataContractJsonSerializer序列化后的结果:{0},长度:{1}", result, resultLength);
}
//JSON反序列化
byte[] buffer = EncodingUTFGetBytes(result);
using (MemoryStream stream =new MemoryStream(buffer))
{
user = serializerReadObject(stream) as User;
ConsoleWriteLine("使用DataContractJsonSerializer反序列化后的结果:UserId:{0},UserName:{1},CreateDate:{2},Priority:{3}", userUserId, userUserName, userCreateDate, userPriority);
}
}
publicstaticvoid JsonConvertDemo()
{
User user =new User { UserId =1, UserName ="李刚", CreateDate = DateTimeNowAddYears(-30), Birthday = DateTimeNowAddYears(-50), Priority = PriorityBelowNormal, Salary =5000 };
//JsonConvert类在NewtonsoftJsonNetdll中,注意到http://wwwcodeplexcom/json/下载这个dll并添加这个引用
//JSON序列化
string result = JsonConvertSerializeObject(user);
ConsoleWriteLine("使用JsonConvert序列化后的结果:{0},长度:{1}", result, resultLength);
//JSON反序列化
user = JsonConvertDeserializeObject<User>(result);
ConsoleWriteLine("使用JsonConvert反序列化后的结果:UserId:{0},UserName:{1},CreateDate:{2},Priority:{3}", userUserId, userUserName, userCreateDate, userPriority);
}
publicstaticvoid JsonConvertLinqDemo()
{
User user =new User { UserId =1, UserName ="周公", CreateDate = DateTimeNowAddYears(-8), Birthday = DateTimeNowAddYears(-32), Priority = PriorityLowest, Salary =500, Urls =new List<string> { "http://zhoufoxcnblog51ctocom", "https://www.jb51.net" } };
//JsonConvert类在NewtonsoftJsonNetdll中,注意到http://wwwcodeplexcom/json/下载这个dll并添加这个引用
//JSON序列化
string result = JsonConvertSerializeObject(user);
ConsoleWriteLine("使用JsonConvert序列化后的结果:{0},长度:{1}", result, resultLength);
//使用Linq to JSON
JObject jobject = JObjectParse(result);
JToken token = jobject["Urls"];
List<string> urlList =new List<string>();
foreach (JToken t in token)
{
urlListAdd(tToString());
}
ConsoleWrite("使用Linq to JSON反序列化后的结果:[");
for (int i =0; i < urlListCount -1;i++ )
{
ConsoleWrite(urlList[i] +",");
}
ConsoleWriteLine(urlList[urlListCount -1] +"]");
}
}
[DataContract]
publicclass User
{
///<summary>
/// 编号
///</summary>
[DataMember]
publicint UserId { get; set; }
///<summary>
/// 用户名
///</summary>
[DataMember]
publicstring UserName { get; set; }
///<summary>
/// 创建时间
///</summary>
[DataMember]
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime CreateDate { get; set; }
///<summary>
/// 生日
///</summary>
[DataMember]
[JsonConverter(typeof(JavaScriptDateTimeConverter))]
public DateTime Birthday { get; set; }
///<summary>
/// 相关URL
///</summary>
[DataMember]
public List<string> Urls { get; set; }
///<summary>
/// 薪水
///</summary>
[ScriptIgnore]//使用JavaScriptSerializer序列化时不序列化此字段
[IgnoreDataMember]//使用DataContractJsonSerializer序列化时不序列化此字段
[JsonIgnore]//使用JsonConvert序列化时不序列化此字段
publicint Salary { get; set; }
///<summary>
/// 权利级别
///</summary>
[DataMember]
public Priority Priority { get; set; }
public User()
{
Urls =new List<string>();
}
}
///<summary>
/// 权利级别
///</summary>
publicenum Priority:byte
{
Lowest=0x1,
BelowNormal=0x2,
Normal=0x4,
AboveNormal=0x8,
Highest=0x16
}
}
程序的运行结果如下:
1.使用JavaScriptSerializer序列化后的结果:{"UserId":1,"UserName":"李刚","CreateDate":"\/Date(353521211984)\/","Birthday":"\/Date(-277630788015)\/","Urls":[],"Priority":22},长度:127
2.使用JavaScriptSerializer反序列化后的结果:UserId:1,UserName:李刚,CreateDate:1981-3-15 16:20:11,Priority:Highest
3.使用DataContractJsonSerializer序列化后的结果:{"Birthday":"\/Date(-277630787953+0800)\/","CreateDate":"\/Date(353521212046+0800)\/","Priority":8,"Urls":[],"UserId":1,"UserName":"李刚"},长度:136
4.使用DataContractJsonSerializer反序列化后的结果:UserId:1,UserName:李刚,CreateDate:1981-3-16 0:20:12,Priority:AboveNormal
5.使用JsonConvert序列化后的结果:{"UserId":1,"UserName":"李刚","CreateDate":"1981-03-16T00:20:12.1875+08:00","Birthday":new Date(-277630787812),"Urls":[],"Priority":2},长度:132
6.使用JsonConvert反序列化后的结果:UserId:1,UserName:李刚,CreateDate:1981-3-16 0:20:12,Priority:BelowNormal
7.使用JsonConvert序列化后的结果:{"UserId":1,"UserName":"周公","CreateDate":"2003-03-16T00:20:12.40625+08:00","Birthday":new Date(290362812406),"Urls":["http://office.jb51.net","https://www.jb51.net/web"],"Priority":1},长度:198
8.使用Linq to JSON反序列化后的结果:["http://office.jb51.net",https://www.jb51.net/web]
总结:通过上面的例子大家可以看出Newtonsoft类库提供的JSON序列化和反序列的方式更加灵活,在实际开发中周公也一直使用Newtonsoft作为JSON序列化和反序列化的不二选择。
JSON(JavaScript Object Notation)是一种轻量级轻量级的数据交换格式,并且它独立于编程语言,与XML序列化相比,JSON序列化后产生的数据一般要比XML序列化后数据体积小,所以在Facebook等知名网站中都采用了JSON作为数据交换方式。在NET中有三种常用的JSON序列化的类,分别是 SystemWebScriptSerializationJavaScriptSerializer类、SystemRuntimeSerializationJsonDataContractJsonSerializer类和NewtonsoftJsonJsonConvert类。
为了便于下面的演示,下面提供一个类的代码:
复制代码 代码如下:
[DataContract]
publicclass User
{
///<summary>
/// 编号
///</summary>
[DataMember]
publicint UserId { get; set; }
///<summary>
/// 用户名
///</summary>
[DataMember]
publicstring UserName { get; set; }
///<summary>
/// 创建时间
///</summary>
[DataMember]
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime CreateDate { get; set; }
///<summary>
/// 生日
///</summary>
[DataMember]
[JsonConverter(typeof(JavaScriptDateTimeConverter))]
public DateTime Birthday { get; set; }
///<summary>
/// 相关URL
///</summary>
[DataMember]
public List<string> Urls { get; set; }
///<summary>
/// 薪水
///</summary>
//[ScriptIgnore]//使用JavaScriptSerializer序列化时不序列化此字段
//[IgnoreDataMember]//使用DataContractJsonSerializer序列化时不序列化此字段
//[JsonIgnore]//使用JsonConvert序列化时不序列化此字段
publicint Salary { get; set; }
///<summary>
/// 权利级别
///</summary>
[DataMember]
public Priority Priority { get; set; }
public User()
{
Urls =new List<string>();
}
}
///<summary>
/// 权利级别
///</summary>
publicenum Priority:byte
{
Lowest=0x1,
BelowNormal=0x2,
Normal=0x4,
AboveNormal=0x8,
Highest=0x16
}
使用SystemWebScriptSerializationJavaScriptSerializer类
SystemWebScriptSerializationJavaScriptSerializer类是NET类库中自带的一种JSON序列化实现,在NET Framework5及以后版本中可以使用这个类,这个类位于SystemWebExtensionsdll中,使用这个类是必须添加对这个dll的引用。
下面的代码是使用JavaScriptSerializer进行序列化和反序列化的例子:
复制代码 代码如下:
publicstaticvoid JavaScriptSerializerDemo()
{
User user =new User { UserId =1, UserName ="李刚", CreateDate = DateTimeNowAddYears(-30),Birthday=DateTimeNowAddYears(-50), Priority = PriorityHighest, Salary =500000 };
//JavaScriptSerializer类在SystemWebExtensionsdll中,注意添加这个引用
JavaScriptSerializer serializer =new JavaScriptSerializer();
//JSON序列化
string result=serializerSerialize(user);
ConsoleWriteLine("使用JavaScriptSerializer序列化后的结果:{0},长度:{1}", result, resultLength);
//JSON反序列化
user = serializerDeserialize<User>(result);
ConsoleWriteLine("使用JavaScriptSerializer反序列化后的结果:UserId:{0},UserName: {1},CreateDate:{2},Priority:{3}", userUserId, userUserName, userCreateDate, userPriority);
}
说明:如果不想序列化某个字段,可以在字段前面加[JsonIgnore]标记。
使用SystemRuntimeSerializationJsonDataContractJsonSerializer类
SystemRuntimeSerializationJsonDataContractJsonSerializer类位于SystemServiceModelWebdll中,使用这个类时除了需要添加对SystemServiceModelWebdll的引用之外,还需要添加SystemRuntimeSerializationdll的引用,注意这个类也是在NET Framework5及以后版本中可以使用。
下面是使用DataContractJsonSerializer类的例子:
复制代码 代码如下:
publicstaticvoid DataContractJsonSerializerDemo()
{
User user =new User { UserId =1, UserName ="李刚", CreateDate = DateTimeNowAddYears(-30), Birthday = DateTimeNowAddYears(-50), Priority = PriorityAboveNormal, Salary =50000 };
string result =stringEmpty;
//DataContractJsonSerializer类在SystemServiceModelWebdll中,注意添加这个引用
DataContractJsonSerializer serializer =new DataContractJsonSerializer(typeof(User));
using (MemoryStream stream =new MemoryStream())
{
//JSON序列化
serializerWriteObject(stream, user);
result = EncodingUTFGetString(streamToArray());
ConsoleWriteLine("使用DataContractJsonSerializer序列化后的结果:{0},长度:{1}", result, resultLength);
}
//JSON反序列化
byte[] buffer = EncodingUTFGetBytes(result);
using (MemoryStream stream =new MemoryStream(buffer))
{
user = serializerReadObject(stream) as User;
ConsoleWriteLine("使用DataContractJsonSerializer反序列化后的结果:UserId: {0},UserName:{1},CreateDate:{2},Priority:{3}", userUserId, userUserName, userCreateDate, userPriority);
}
}
注意:要使用DataContractJsonSerializer类进行序列化和反序列化,必须给类加上[DataContract]属性,对要序列化的字段加上[DataMember]属性,如果不想序列化某个字段或者属性,可以加上[IgnoreDataMember]属性。
使用NewtonsoftJsonJsonConvert类
NewtonsoftJsonJsonConvert类是非微软提供的一个JSON序列化和反序列的开源免费的类库(下载网址是:http://wwwcodeplexcom/json/),它提供了更灵活的序列化和反序列化控制,并且如果你的开发环境使用的是NET Framework5及以后版本的话,你就可以使用Linq to JSON,这样一来面对一大段的数据不必一一解析,你可以使用Linq to JSON解析出你关心的那部分即可,非常方便。
下面是使用NewtonsoftJsonJsonConvert类的例子:
复制代码 代码如下:
publicstaticvoid JsonConvertDemo()
{
User user =new User { UserId =1, UserName ="李刚", CreateDate = DateTimeNowAddYears(-30), Birthday = DateTimeNowAddYears(-50), Priority = PriorityBelowNormal, Salary =5000 };
//JsonConvert类在NewtonsoftJsonNetdll中,注意到http://wwwcodeplexcom/json/下载这个dll并添加这个引用
//JSON序列化
string result = JsonConvertSerializeObject(user);
ConsoleWriteLine("使用JsonConvert序列化后的结果:{0},长度:{1}", result, resultLength);
//JSON反序列化
user = JsonConvertDeserializeObject<User>(result);
ConsoleWriteLine("使用JsonConvert反序列化后的结果:UserId:{0},UserName: {1},CreateDate:{2},Priority:{3}", userUserId, userUserName, userCreateDate, userPriority);
}
publicstaticvoid JsonConvertLinqDemo()
{
User user =new User { UserId =1, UserName ="周公", CreateDate = DateTimeNowAddYears(-8), Birthday = DateTimeNowAddYears(-32), Priority = PriorityLowest, Salary =500, Urls =new List<string> { "http://zhoufoxcnblog51ctocom", "https://www.jb51.net" } };
//JsonConvert类在NewtonsoftJsonNetdll中,注意到http://wwwcodeplexcom/json/下载这个dll并添加这个引用
//JSON序列化
string result = JsonConvertSerializeObject(user);
ConsoleWriteLine("使用JsonConvert序列化后的结果:{0},长度:{1}", result, resultLength);
//使用Linq to JSON
JObject jobject = JObjectParse(result);
JToken token = jobject["Urls"];
List<string> urlList =new List<string>();
foreach (JToken t in token)
{
urlListAdd(tToString());
}
ConsoleWrite("使用Linq to JSON反序列化后的结果:[");
for (int i =0; i < urlListCount -1;i++ )
{
ConsoleWrite(urlList[i] +",");
}
ConsoleWriteLine(urlList[urlListCount -1] +"]");
}
注意:如果有不需要序列化的字段,可以给该字段添加[JsonIgnore]标记。在Newtonsoft这个类库中对于日期的序列化有多种方式,可以类的DataTime成员添加上对应的标记,这样在进行序列化和反序列化时就会按照指定的方式进行,在本例中User类的CreateDate属性添加的属性是[JsonConverter(typeof(IsoDateTimeConverter))],而Birthday属性添加的属性是[JsonConverter(typeof(JavaScriptDateTimeConverter))],从序列化的结果可以看出来它们最终的表现形式并不一样。
本文中所有的示例代码如下:
复制代码 代码如下:
using System;
using SystemCollectionsGeneric;
using SystemLinq;
using SystemText;
using SystemWebScriptSerialization;
using SystemRuntimeSerializationJson;
using SystemIO;
using SystemRuntimeSerialization;
using NewtonsoftJson;
using NewtonsoftJsonLinq;
using NewtonsoftJsonConverters;
namespace JSONDemo
{
class Program
{
staticvoid Main(string[] args)
{
JavaScriptSerializerDemo();
DataContractJsonSerializerDemo();
JsonConvertDemo();
JsonConvertLinqDemo();
ConsoleReadLine();
}
publicstaticvoid JavaScriptSerializerDemo()
{
User user =new User { UserId =1, UserName ="李刚", CreateDate = DateTimeNowAddYears(-30),Birthday=DateTimeNowAddYears(-50), Priority = PriorityHighest, Salary =500000 };
//JavaScriptSerializer类在SystemWebExtensionsdll中,注意添加这个引用
JavaScriptSerializer serializer =new JavaScriptSerializer();
//JSON序列化
string result=serializerSerialize(user);
ConsoleWriteLine("使用JavaScriptSerializer序列化后的结果:{0},长度:{1}", result, resultLength);
//JSON反序列化
user = serializerDeserialize<User>(result);
ConsoleWriteLine("使用JavaScriptSerializer反序列化后的结果:UserId:{0},UserName:{1},CreateDate:{2},Priority:{3}", userUserId, userUserName, userCreateDate, userPriority);
}
publicstaticvoid DataContractJsonSerializerDemo()
{
User user =new User { UserId =1, UserName ="李刚", CreateDate = DateTimeNowAddYears(-30), Birthday = DateTimeNowAddYears(-50), Priority = PriorityAboveNormal, Salary =50000 };
string result =stringEmpty;
//DataContractJsonSerializer类在SystemServiceModelWebdll中,注意添加这个引用
DataContractJsonSerializer serializer =new DataContractJsonSerializer(typeof(User));
using (MemoryStream stream =new MemoryStream())
{
//JSON序列化
serializerWriteObject(stream, user);
result = EncodingUTFGetString(streamToArray());
ConsoleWriteLine("使用DataContractJsonSerializer序列化后的结果:{0},长度:{1}", result, resultLength);
}
//JSON反序列化
byte[] buffer = EncodingUTFGetBytes(result);
using (MemoryStream stream =new MemoryStream(buffer))
{
user = serializerReadObject(stream) as User;
ConsoleWriteLine("使用DataContractJsonSerializer反序列化后的结果:UserId:{0},UserName:{1},CreateDate:{2},Priority:{3}", userUserId, userUserName, userCreateDate, userPriority);
}
}
publicstaticvoid JsonConvertDemo()
{
User user =new User { UserId =1, UserName ="李刚", CreateDate = DateTimeNowAddYears(-30), Birthday = DateTimeNowAddYears(-50), Priority = PriorityBelowNormal, Salary =5000 };
//JsonConvert类在NewtonsoftJsonNetdll中,注意到http://wwwcodeplexcom/json/下载这个dll并添加这个引用
//JSON序列化
string result = JsonConvertSerializeObject(user);
ConsoleWriteLine("使用JsonConvert序列化后的结果:{0},长度:{1}", result, resultLength);
//JSON反序列化
user = JsonConvertDeserializeObject<User>(result);
ConsoleWriteLine("使用JsonConvert反序列化后的结果:UserId:{0},UserName:{1},CreateDate:{2},Priority:{3}", userUserId, userUserName, userCreateDate, userPriority);
}
publicstaticvoid JsonConvertLinqDemo()
{
User user =new User { UserId =1, UserName ="周公", CreateDate = DateTimeNowAddYears(-8), Birthday = DateTimeNowAddYears(-32), Priority = PriorityLowest, Salary =500, Urls =new List<string> { "http://zhoufoxcnblog51ctocom", "https://www.jb51.net" } };
//JsonConvert类在NewtonsoftJsonNetdll中,注意到http://wwwcodeplexcom/json/下载这个dll并添加这个引用
//JSON序列化
string result = JsonConvertSerializeObject(user);
ConsoleWriteLine("使用JsonConvert序列化后的结果:{0},长度:{1}", result, resultLength);
//使用Linq to JSON
JObject jobject = JObjectParse(result);
JToken token = jobject["Urls"];
List<string> urlList =new List<string>();
foreach (JToken t in token)
{
urlListAdd(tToString());
}
ConsoleWrite("使用Linq to JSON反序列化后的结果:[");
for (int i =0; i < urlListCount -1;i++ )
{
ConsoleWrite(urlList[i] +",");
}
ConsoleWriteLine(urlList[urlListCount -1] +"]");
}
}
[DataContract]
publicclass User
{
///<summary>
/// 编号
///</summary>
[DataMember]
publicint UserId { get; set; }
///<summary>
/// 用户名
///</summary>
[DataMember]
publicstring UserName { get; set; }
///<summary>
/// 创建时间
///</summary>
[DataMember]
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime CreateDate { get; set; }
///<summary>
/// 生日
///</summary>
[DataMember]
[JsonConverter(typeof(JavaScriptDateTimeConverter))]
public DateTime Birthday { get; set; }
///<summary>
/// 相关URL
///</summary>
[DataMember]
public List<string> Urls { get; set; }
///<summary>
/// 薪水
///</summary>
[ScriptIgnore]//使用JavaScriptSerializer序列化时不序列化此字段
[IgnoreDataMember]//使用DataContractJsonSerializer序列化时不序列化此字段
[JsonIgnore]//使用JsonConvert序列化时不序列化此字段
publicint Salary { get; set; }
///<summary>
/// 权利级别
///</summary>
[DataMember]
public Priority Priority { get; set; }
public User()
{
Urls =new List<string>();
}
}
///<summary>
/// 权利级别
///</summary>
publicenum Priority:byte
{
Lowest=0x1,
BelowNormal=0x2,
Normal=0x4,
AboveNormal=0x8,
Highest=0x16
}
}
程序的运行结果如下:
1.使用JavaScriptSerializer序列化后的结果:{"UserId":1,"UserName":"李刚","CreateDate":"\/Date(353521211984)\/","Birthday":"\/Date(-277630788015)\/","Urls":[],"Priority":22},长度:127
2.使用JavaScriptSerializer反序列化后的结果:UserId:1,UserName:李刚,CreateDate:1981-3-15 16:20:11,Priority:Highest
3.使用DataContractJsonSerializer序列化后的结果:{"Birthday":"\/Date(-277630787953+0800)\/","CreateDate":"\/Date(353521212046+0800)\/","Priority":8,"Urls":[],"UserId":1,"UserName":"李刚"},长度:136
4.使用DataContractJsonSerializer反序列化后的结果:UserId:1,UserName:李刚,CreateDate:1981-3-16 0:20:12,Priority:AboveNormal
5.使用JsonConvert序列化后的结果:{"UserId":1,"UserName":"李刚","CreateDate":"1981-03-16T00:20:12.1875+08:00","Birthday":new Date(-277630787812),"Urls":[],"Priority":2},长度:132
6.使用JsonConvert反序列化后的结果:UserId:1,UserName:李刚,CreateDate:1981-3-16 0:20:12,Priority:BelowNormal
7.使用JsonConvert序列化后的结果:{"UserId":1,"UserName":"周公","CreateDate":"2003-03-16T00:20:12.40625+08:00","Birthday":new Date(290362812406),"Urls":["http://office.jb51.net","https://www.jb51.net/web"],"Priority":1},长度:198
8.使用Linq to JSON反序列化后的结果:["http://office.jb51.net",https://www.jb51.net/web]
总结:通过上面的例子大家可以看出Newtonsoft类库提供的JSON序列化和反序列的方式更加灵活,在实际开发中周公也一直使用Newtonsoft作为JSON序列化和反序列化的不二选择。
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
暂无评论...
更新日志
2024年11月29日
2024年11月29日
- 凤飞飞《我们的主题曲》飞跃制作[正版原抓WAV+CUE]
- 刘嘉亮《亮情歌2》[WAV+CUE][1G]
- 红馆40·谭咏麟《歌者恋歌浓情30年演唱会》3CD[低速原抓WAV+CUE][1.8G]
- 刘纬武《睡眠宝宝竖琴童谣 吉卜力工作室 白噪音安抚》[320K/MP3][193.25MB]
- 【轻音乐】曼托凡尼乐团《精选辑》2CD.1998[FLAC+CUE整轨]
- 邝美云《心中有爱》1989年香港DMIJP版1MTO东芝首版[WAV+CUE]
- 群星《情叹-发烧女声DSD》天籁女声发烧碟[WAV+CUE]
- 刘纬武《睡眠宝宝竖琴童谣 吉卜力工作室 白噪音安抚》[FLAC/分轨][748.03MB]
- 理想混蛋《Origin Sessions》[320K/MP3][37.47MB]
- 公馆青少年《我其实一点都不酷》[320K/MP3][78.78MB]
- 群星《情叹-发烧男声DSD》最值得珍藏的完美男声[WAV+CUE]
- 群星《国韵飘香·贵妃醉酒HQCD黑胶王》2CD[WAV]
- 卫兰《DAUGHTER》【低速原抓WAV+CUE】
- 公馆青少年《我其实一点都不酷》[FLAC/分轨][398.22MB]
- ZWEI《迟暮的花 (Explicit)》[320K/MP3][57.16MB]