We know that in NET, we have a variety of Object serialization methods, such as XML serialization and Binary serialization. XML serialization is a common way to transmit data between languages. In addition to the two serialization methods, JSON serialization can also be used in NET.
JSON (JavaScript Object Notation) is a lightweight and lightweight data exchange format, which is independent of programming languages, compared with XML serialization, the data produced after JSON serialization is generally smaller than the data after XML serialization. Therefore, JSON is used as a data exchange method in Facebook and other well-known websites. There are three common JSON serialization classes in NET: SystemWebScriptSerializationJavaScriptSerializer class, SystemRuntimeSerializationJsonDataContractJsonSerializer class, And NewtonsoftJsonJsonConvert class.
In order to facilitate the following demonstration, the following provides the code of a class:
Copy codeThe Code is as follows:
[DataContract]
Publicclass User
{
/// <Summary>
/// No.
/// </Summary>
[DataMember]
Publicint UserId {get; set ;}
/// <Summary>
/// User Name
/// </Summary>
[DataMember]
Publicstring UserName {get; set ;}
/// <Summary>
/// Creation Time
/// </Summary>
[DataMember]
[JsonConverter (typeof (IsoDateTimeConverter)]
Public DateTime CreateDate {get; set ;}
/// <Summary>
/// Birthday
/// </Summary>
[DataMember]
[JsonConverter (typeof (JavaScriptDateTimeConverter)]
Public DateTime Birthday {get; set ;}
/// <Summary>
/// Related URL
/// </Summary>
[DataMember]
Public List <string> Urls {get; set ;}
/// <Summary>
/// Salary
/// </Summary>
// [ScriptIgnore] // This field is not serialized when being serialized using JavaScriptSerializer
// [IgnoreDataMember] // This field is not serialized when DataContractJsonSerializer is used for serialization.
// [JsonIgnore] // This field is not serialized when JsonConvert is used for serialization.
Publicint Salary {get; set ;}
/// <Summary>
/// Permission level
/// </Summary>
[DataMember]
Public Priority {get; set ;}
Public User ()
{
Urls = new List <string> ();
}
}
/// <Summary>
/// Permission level
/// </Summary>
Publicenum Priority: byte
{
Lowest = 0x1,
BelowNormal = 0x2,
Normal = 0x4,
AboveNormal = 0x8,
Highest = 0x16
}
Use SystemWebScriptSerializationJavaScriptSerializer class
The SystemWebScriptSerializationJavaScriptSerializer class is a built-in JSON serialization implementation in the NET class library. This class can be used in NET Framework5 and later versions. This class is located in SystemWebExtensionsdll, to use this class, you must add a reference to this dll.
The following code uses JavaScriptSerializer for serialization and deserialization:
Copy codeThe Code is as follows:
Publicstaticvoid JavaScriptSerializerDemo ()
{
User user = new User {UserId = 1, UserName = "", CreateDate = DateTimeNowAddYears (-30), Birthday = DateTimeNowAddYears (-50), Priority = PriorityHighest, salary = 500000 };
// The JavaScriptSerializer class is in SystemWebExtensionsdll. Add this reference.
JavaScriptSerializer serializer = new JavaScriptSerializer ();
// JSON serialization
String result = serializerSerialize (user );
ConsoleWriteLine ("serialized result using JavaScriptSerializer: {0}, Length: {1}", result, resultLength );
// JSON deserialization
User = serializerDeserialize <User> (result );
ConsoleWriteLine ("result after deserialization using JavaScriptSerializer: UserId: {0}, UserName: {1}, CreateDate: {2}, Priority: {3}", userUserId, userUserName, userCreateDate, userPriority );
}
Note: If you do not want to serialize a field, you can add the [JsonIgnore] Mark before the field.
Use SystemRuntimeSerializationJsonDataContractJsonSerializer class
The category class is located in SystemServiceModelWebdll. To use this class, in addition to adding a reference to SystemServiceModelWebdll, you also need to add a reference to SystemRuntimeSerializationdll. Note that this class is also available in NET Framework5 and later versions.
The following is an example of using the DataContractJsonSerializer class:
Copy codeThe Code is as follows:
Publicstaticvoid DataContractJsonSerializerDemo ()
{
User user = new User {UserId = 1, UserName = "", CreateDate = DateTimeNowAddYears (-30), Birthday = DateTimeNowAddYears (-50), Priority = PriorityAboveNormal, salary = 50000 };
String result = stringEmpty;
// The DataContractJsonSerializer class is in SystemServiceModelWebdll. Add this reference.
DataContractJsonSerializer serializer = new DataContractJsonSerializer (typeof (User ));
Using (MemoryStream stream = new MemoryStream ())
{
// JSON serialization
SerializerWriteObject (stream, user );
Result = EncodingUTFGetString (streamToArray ());
ConsoleWriteLine ("result after serialization using DataContractJsonSerializer: {0}, Length: {1}", result, resultLength );
}
// JSON deserialization
Byte [] buffer = EncodingUTFGetBytes (result );
Using (MemoryStream stream = new MemoryStream (buffer ))
{
User = serializerReadObject (stream) as User;
ConsoleWriteLine ("result after deserialization using DataContractJsonSerializer: UserId: {0}, UserName: {1}, CreateDate: {2}, Priority: {3}", userUserId, userUserName, userCreateDate, userPriority );
}
}
Note: To use the DataContractJsonSerializer class for serialization and deserialization, you must add the [DataContract] attribute to the class and add the [DataMember] attribute to the field to be serialized. If you do not want to serialize a field or attribute, you can add the [IgnoreDataMember] attribute.
Use NewtonsoftJsonJsonConvert class
The NewtonsoftJsonJsonConvert class is a non-Microsoft open-source free class library for JSON serialization and deserialization (download URL: http: // wwwcodeplexcom/json /), it provides more flexible serialization and deserialization control. If your development environment uses NET Framework5 or a later version, you can use Linq to JSON, in this way, you do not need to parse a large data segment one by one. You can use Linq to JSON to parse the part you are concerned about, which is very convenient.
The following example uses the NewtonsoftJsonJsonConvert class:
Copy codeThe Code is as follows:
Publicstaticvoid JsonConvertDemo ()
{
User user = new User {UserId = 1, UserName = "", CreateDate = DateTimeNowAddYears (-30), Birthday = DateTimeNowAddYears (-50), Priority = PriorityBelowNormal, salary = 5000 };
// In NewtonsoftJsonNetdll, The JsonConvert class notices that http: // wwwcodeplexcom/json/downloads the dll and adds this reference.
// JSON serialization
String result = JsonConvertSerializeObject (user );
ConsoleWriteLine ("result after JsonConvert serialization: {0}, Length: {1}", result, resultLength );
// JSON deserialization
User = JsonConvertDeserializeObject <User> (result );
ConsoleWriteLine ("result after JsonConvert deserialization: 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", "http://www.jb51.net "}};
// In NewtonsoftJsonNetdll, The JsonConvert class notices that http: // wwwcodeplexcom/json/downloads the dll and adds this reference.
// JSON serialization
String result = JsonConvertSerializeObject (user );
ConsoleWriteLine ("result after JsonConvert serialization: {0}, Length: {1}", result, resultLength );
// Use 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 ("result after deserialization using Linq to JSON :[");
For (int I = 0; I <urlListCount-1; I ++)
{
ConsoleWrite (urlList [I] + ",");
}
ConsoleWriteLine (urlList [urlListCount-1] + "]");
}
Note: If a field does not need to be serialized, you can add the [JsonIgnore] mark to the field. There are multiple methods for date serialization in the Newtonsoft class library. You can add the corresponding tag to the DataTime member of the class, so that the serialization and deserialization will follow the specified method, in this example, the CreateDate attribute of the User class is added to [JsonConverter (typeof (IsoDateTimeConverter)], and the Birthday attribute is added to [JsonConverter (typeof (JavaScriptDateTimeConverter)], from the serialized results, we can see that their final representations are not the same.
All the sample code in this article is as follows:
Copy codeThe Code is as follows:
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 };
// The JavaScriptSerializer class is in SystemWebExtensionsdll. Add this reference.
JavaScriptSerializer serializer = new JavaScriptSerializer ();
// JSON serialization
String result = serializerSerialize (user );
ConsoleWriteLine ("serialized result using JavaScriptSerializer: {0}, Length: {1}", result, resultLength );
// JSON deserialization
User = serializerDeserialize <User> (result );
ConsoleWriteLine ("result after deserialization using 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;
// The DataContractJsonSerializer class is in SystemServiceModelWebdll. Add this reference.
DataContractJsonSerializer serializer = new DataContractJsonSerializer (typeof (User ));
Using (MemoryStream stream = new MemoryStream ())
{
// JSON serialization
SerializerWriteObject (stream, user );
Result = EncodingUTFGetString (streamToArray ());
ConsoleWriteLine ("result after serialization using DataContractJsonSerializer: {0}, Length: {1}", result, resultLength );
}
// JSON deserialization
Byte [] buffer = EncodingUTFGetBytes (result );
Using (MemoryStream stream = new MemoryStream (buffer ))
{
User = serializerReadObject (stream) as User;
ConsoleWriteLine ("result after deserialization using 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 };
// In NewtonsoftJsonNetdll, The JsonConvert class notices that http: // wwwcodeplexcom/json/downloads the dll and adds this reference.
// JSON serialization
String result = JsonConvertSerializeObject (user );
ConsoleWriteLine ("result after JsonConvert serialization: {0}, Length: {1}", result, resultLength );
// JSON deserialization
User = JsonConvertDeserializeObject <User> (result );
ConsoleWriteLine ("result after JsonConvert deserialization: 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", "http://www.jb51.net "}};
// In NewtonsoftJsonNetdll, The JsonConvert class notices that http: // wwwcodeplexcom/json/downloads the dll and adds this reference.
// JSON serialization
String result = JsonConvertSerializeObject (user );
ConsoleWriteLine ("result after JsonConvert serialization: {0}, Length: {1}", result, resultLength );
// Use 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 ("result after deserialization using Linq to JSON :[");
For (int I = 0; I <urlListCount-1; I ++)
{
ConsoleWrite (urlList [I] + ",");
}
ConsoleWriteLine (urlList [urlListCount-1] + "]");
}
}
[DataContract]
Publicclass User
{
/// <Summary>
/// No.
/// </Summary>
[DataMember]
Publicint UserId {get; set ;}
/// <Summary>
/// User Name
/// </Summary>
[DataMember]
Publicstring UserName {get; set ;}
/// <Summary>
/// Creation Time
/// </Summary>
[DataMember]
[JsonConverter (typeof (IsoDateTimeConverter)]
Public DateTime CreateDate {get; set ;}
/// <Summary>
/// Birthday
/// </Summary>
[DataMember]
[JsonConverter (typeof (JavaScriptDateTimeConverter)]
Public DateTime Birthday {get; set ;}
/// <Summary>
/// Related URL
/// </Summary>
[DataMember]
Public List <string> Urls {get; set ;}
/// <Summary>
/// Salary
/// </Summary>
[ScriptIgnore] // This field is not serialized when using JavaScriptSerializer for serialization.
[IgnoreDataMember] // This field is not serialized when DataContractJsonSerializer is used for serialization.
[JsonIgnore] // This field is not serialized when JsonConvert is used for serialization.
Publicint Salary {get; set ;}
/// <Summary>
/// Permission level
/// </Summary>
[DataMember]
Public Priority {get; set ;}
Public User ()
{
Urls = new List <string> ();
}
}
/// <Summary>
/// Permission level
/// </Summary>
Publicenum Priority: byte
{
Lowest = 0x1,
BelowNormal = 0x2,
Normal = 0x4,
AboveNormal = 0x8,
Highest = 0x16
}
}
The running result of the program is as follows::
1. serialized result using JavaScriptSerializer: {"UserId": 1, "UserName": "Li Gang", "CreateDate": "\/Date (353521211984 )\/", "Birthday": "\/Date (-277630788015) \/", "Urls": [], "Priority": 22}, Length: 127
2. Result of deserialization using JavaScriptSerializer: UserId: 1, UserName: Li Gang, CreateDate: 16:20:11, Priority: Highest
3. serialized result using DataContractJsonSerializer: {"Birthday": "\/Date (-277630787953 + 0800) \/", "CreateDate": "\/Date (353521212046 + 0800) \/"," Priority ": 8," Urls ": []," UserId ": 1," UserName ":" Li Gang "}, Length: 136
4. Result of deserialization using DataContractJsonSerializer: UserId: 1, UserName: Li Gang, CreateDate: 1981-3-16 0:20:12, Priority: AboveNormal
5. result After JsonConvert serialization: {"UserId": 1, "UserName": "", "CreateDate": "1981-03-16T00: 20: 12.1875 + 08: 00 ", "Birthday": new Date (-277630787812), "Urls": [], "Priority": 2}, Length: 132
6. Result After deserialization using JsonConvert: UserId: 1, UserName: Li Gang, CreateDate: 0:20:12, Priority: BelowNormal
7. result After JsonConvert serialization: {"UserId": 1, "UserName": "", "CreateDate": "2003-03-16T00: 20: 12.40625 + 08: 00 ", "Birthday": new Date (290362812406), "Urls": ["http://office.jb51.net", "http://www.jb51.net/web"], "Priority": 1}, Length: 198
8. Results After deserialization using Linq to JSON: ["http://office.jb51.net", http://www.jb51.net/web]
Summary: The preceding example shows that the Newtonsoft Class Library provides more flexible JSON serialization and deserialization methods, in actual development, Zhou Gong has always used Newtonsoft as the best choice for JSON serialization and deserialization.