Use JSON as a data interchange format instance in. NET Demo _ Practical Tips

Source: Internet
Author: User
Tags datetime object serialization serialization
We know that in net we have a variety of object serialization methods, such as XML serialization, binary serialization, where XML serialization is a more common way of passing data between languages. In addition to these two serialization methods, JSON serialization can also be used in net.

JSON (JavaScript Object notation) is a lightweight, lightweight data interchange format, and it is independent of the programming language, and the data produced after JSON serialization is typically smaller than the data volume after XML serialization, compared to XML serialization, So well-known websites such as Facebook have used JSON as a way of exchanging data. There are three commonly used JSON serialization classes in net, namely the Systemwebscriptserializationjavascriptserializer class, Systemruntimeserializationjsondatacontractjsonserializer class and Newtonsoftjsonjsonconvert class.

For the following demo, the code for a class is provided below

Copy Code code as follows:

[DataContract]
Publicclass User
{
<summary>
Number
</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 URLs
</summary>
[DataMember]
Public list<string> URL {get; set;}
<summary>
Salary
</summary>
[scriptignore]//This field is not serialized when using JavaScriptSerializer serialization
[ignoredatamember]//This field is not serialized when using DataContractJsonSerializer serialization
[jsonignore]//This field is not serialized when using JsonConvert serialization
Publicint Salary {get; set;}
<summary>
Right level
</summary>
[DataMember]
Public Priority Priority {get; set;}
Public User ()
{
Urls =new list<string> ();
}
}
<summary>
Right level
</summary>
Publicenum Priority:byte
{
lowest=0x1,
BELOWNORMAL=0X2,
normal=0x4,
abovenormal=0x8,
highest=0x16
}

Using the Systemwebscriptserializationjavascriptserializer class
The Systemwebscriptserializationjavascriptserializer class is a JSON serialization implementation from the Net class library, which can be used in net FRAMEWORK5 and later versions. This class is in Systemwebextensionsdll, and using this class you must add a reference to the DLL.
The following code is an example of serialization and deserialization using JavaScriptSerializer:
Copy Code code as follows:

Publicstaticvoid Javascriptserializerdemo ()
{
User User =new User {UserId =1, UserName = "Li Gang", CreateDate = Datetimenowaddyears ( -30), Birthday=datetimenowaddyears (-50), Priority = priorityhighest, Salary = 500000};
JavaScriptSerializer class in Systemwebextensionsdll, note add this reference
JavaScriptSerializer Serializer =new JavaScriptSerializer ();
JSON serialization
String result=serializerserialize (user);
Consolewriteline ("Results after serialization using JavaScriptSerializer: {0}, Length: {1}", result, resultlength);
JSON deserialization
user = serializerdeserialize<user> (result);
Consolewriteline ("Results 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 precede the field with a [Jsonignore] tag.
Using the Systemruntimeserializationjsondatacontractjsonserializer class
The Systemruntimeserializationjsondatacontractjsonserializer class is located in Systemservicemodelwebdll, In addition to adding a reference to Systemservicemodelwebdll, you need to add a Systemruntimeserializationdll reference to this class, and note that this class is also used in net Can be used in FRAMEWORK5 and later versions.
The following are examples of using the DataContractJsonSerializer class:
Copy Code code as follows:

Publicstaticvoid Datacontractjsonserializerdemo ()
{
User User =new User {UserId =1, UserName = "Li Gang", CreateDate = Datetimenowaddyears ( -30), birthday = Datetimenowaddyears (-50 ), Priority = priorityabovenormal, Salary = 50000};
string result =stringempty;
DataContractJsonSerializer class in Systemservicemodelwebdll, note add this reference
DataContractJsonSerializer Serializer =new DataContractJsonSerializer (typeof (User));
using (MemoryStream stream =new MemoryStream ())
{
JSON serialization
Serializerwriteobject (stream, user);
result = Encodingutfgetstring (Streamtoarray ());
Consolewriteline ("Results 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 ("Results after deserialization using DataContractJsonSerializer: UserId: {0},username:{1},createdate:{2},priority:{3}", Useruserid, Userusername, Usercreatedate, userpriority);
}
}

Note: To serialize and deserialize using the DataContractJsonSerializer class, you must add the [DataContract] property to the class, add the [DataMember] property to the field to be serialized, and if you do not want to serialize a field or property, You can add the [Ignoredatamember] property.
Using the Newtonsoftjsonjsonconvert class
The Newtonsoftjsonjsonconvert class is an open-source, free Library of JSON serialization and deserialization (download URL: http://wwwcodeplexcom/json/), which provides more flexible serialization and deserialization control, And if your development environment is using the net Framework5 and later version, you can use LINQ to JSON, so that the face of a large segment of data does not have to one by one parsing, you can use LINQ to JSON parse out the part you care about, very convenient.
The following are examples of using the Newtonsoftjsonjsonconvert class:
Copy Code code as follows:

Publicstaticvoid Jsonconvertdemo ()
{
User User =new User {UserId =1, UserName = "Li Gang", CreateDate = Datetimenowaddyears ( -30), birthday = Datetimenowaddyears (-50 ), Priority = prioritybelownormal, Salary = 5000};
JsonConvert class in Newtonsoftjsonnetdll, note that http://wwwcodeplexcom/json/downloads this DLL and adds this reference
JSON serialization
string result = Jsonconvertserializeobject (user);
Consolewriteline ("Results after serialization using JsonConvert: {0}, Length: {1}", result, resultlength);
JSON deserialization
user = jsonconvertdeserializeobject<user> (result);
Consolewriteline ("Results after deserialization using JsonConvert: Userid:{0},username: {1},createdate:{2},priority:{3}", UserUserId, Userusername, Usercreatedate, userpriority);
}
Publicstaticvoid Jsonconvertlinqdemo ()
{
User User =new User {UserId =1, UserName = "Zhou Gong", CreateDate = Datetimenowaddyears ( -8), birthday = Datetimenowaddyears (-32) , Priority = Prioritylowest, Salary =500, Urls =new list<string> {"http://zhoufoxcnblog51ctocom", "http://www.jb51 . NET "}};
JsonConvert class in Newtonsoftjsonnetdll, note that http://wwwcodeplexcom/json/downloads this DLL and adds this reference
JSON serialization
string result = Jsonconvertserializeobject (user);
Consolewriteline ("Results after serialization using JsonConvert: {0}, Length: {1}", result, resultlength);
Using 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 of deserialization using LINQ to JSON: [");
for (int i =0 i < urllistcount-1;i++)
{
Consolewrite (Urllist[i] + ",");
}
Consolewriteline (Urllist[urllistcount-1] + "]");
}

Note: If you have a field that does not need to be serialized, you can add a [Jsonignore] tag to the field. There are several ways to serialize a date in the Newtonsoft class library, and the corresponding markup can be added to the Datatime member of the class, so that the serialization and deserialization are done in the specified manner, in this case the property of the CreateDate property of the user class is added as [ Jsonconverter (typeof (Isodatetimeconverter))], and the birthday attribute adds a property that is [Jsonconverter ( Javascriptdatetimeconverter)], from the results of serialization can be seen that their final form of expression is not the same.
All the sample code in this article is as follows:
Copy Code code 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 = "Li Gang", CreateDate = Datetimenowaddyears ( -30), Birthday=datetimenowaddyears (-50), Priority = priorityhighest, Salary = 500000};
JavaScriptSerializer class in Systemwebextensionsdll, note add this reference
JavaScriptSerializer Serializer =new JavaScriptSerializer ();
JSON serialization
String result=serializerserialize (user);
Consolewriteline ("Results after serialization using JavaScriptSerializer: {0}, Length: {1}", result, resultlength);
JSON deserialization
user = serializerdeserialize<user> (result);
Consolewriteline (Result of using JavaScriptSerializer deserialization: userid:{0},username:{1},createdate:{2},priority:{3} ", Useruserid, Userusername, Usercreatedate, userpriority);
}
Publicstaticvoid Datacontractjsonserializerdemo ()
{
User User =new User {UserId =1, UserName = "Li Gang", CreateDate = Datetimenowaddyears ( -30), birthday = Datetimenowaddyears (-50 ), Priority = priorityabovenormal, Salary = 50000};
string result =stringempty;
DataContractJsonSerializer class in Systemservicemodelwebdll, note add this reference
DataContractJsonSerializer Serializer =new DataContractJsonSerializer (typeof (User));
using (MemoryStream stream =new MemoryStream ())
{
JSON serialization
Serializerwriteobject (stream, user);
result = Encodingutfgetstring (Streamtoarray ());
Consolewriteline ("Results 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 of using DataContractJsonSerializer deserialization: userid:{0},username:{1},createdate:{2},priority:{3} ", Useruserid, Userusername, Usercreatedate, userpriority);
}
}
Publicstaticvoid Jsonconvertdemo ()
{
User User =new User {UserId =1, UserName = "Li Gang", CreateDate = Datetimenowaddyears ( -30), birthday = Datetimenowaddyears (-50 ), Priority = prioritybelownormal, Salary = 5000};
JsonConvert class in Newtonsoftjsonnetdll, note that http://wwwcodeplexcom/json/downloads this DLL and adds this reference
JSON serialization
string result = Jsonconvertserializeobject (user);
Consolewriteline ("Results after serialization using JsonConvert: {0}, Length: {1}", result, resultlength);
JSON deserialization
user = jsonconvertdeserializeobject<user> (result);
Consolewriteline (Result of using JsonConvert deserialization: userid:{0},username:{1},createdate:{2},priority:{3} ", UserUserId, Userusername, Usercreatedate, userpriority);
}
Publicstaticvoid Jsonconvertlinqdemo ()
{
User User =new User {UserId =1, UserName = "Zhou Gong", CreateDate = Datetimenowaddyears ( -8), birthday = Datetimenowaddyears (-32) , Priority = Prioritylowest, Salary =500, Urls =new list<string> {"http://zhoufoxcnblog51ctocom", "http://www.jb51 . NET "}};
JsonConvert class in Newtonsoftjsonnetdll, note that http://wwwcodeplexcom/json/downloads this DLL and adds this reference
JSON serialization
string result = Jsonconvertserializeobject (user);
Consolewriteline ("Results after serialization using JsonConvert: {0}, Length: {1}", result, resultlength);
Using 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 of deserialization using LINQ to JSON: [");
for (int i =0 i < urllistcount-1;i++)
{
Consolewrite (Urllist[i] + ",");
}
Consolewriteline (Urllist[urllistcount-1] + "]");
}
}
[DataContract]
Publicclass User
{
<summary>
Number
</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 URLs
</summary>
[DataMember]
Public list<string> URL {get; set;}
<summary>
Salary
</summary>
[scriptignore]//This field is not serialized when using JavaScriptSerializer serialization
[ignoredatamember]//This field is not serialized when using DataContractJsonSerializer serialization
[jsonignore]//This field is not serialized when using JsonConvert serialization
Publicint Salary {get; set;}
<summary>
Right level
</summary>
[DataMember]
Public Priority Priority {get; set;}
Public User ()
{
Urls =new list<string> ();
}
}
<summary>
Right 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. Using JavaScriptSerializer Serialization results: {"UserId": 1, "UserName": "Li Gang", "CreateDate": "\/date (353521211984) \/", "Birthday": " \/date ( -277630788015) \/", Urls": [], "Priority": 22}, Length: 127
2. Result of using JavaScriptSerializer deserialization: Userid:1,username: Li Gang, createdate:1981-3-15 16:20:11,priority:highest
3. Result of using DataContractJsonSerializer serialization: {"Birthday": "\/date ( -277630787953+0800) \/", "CreateDate": "\/date" ( 353521212046+0800) \/"," Priority ": 8," Urls ": []," UserId ": 1," UserName ":" Li Gang "}, Length: 136
4. Result of using DataContractJsonSerializer deserialization: Userid:1,username: Li Gang, createdate:1981-3-16 0:20:12,priority:abovenormal
5. Using JsonConvert Serialization results: {"UserId": 1, "UserName": "Li Gang", "CreateDate": "1981-03-16t00:20:12.1875+08:00", "Birthday": New Date ( -277630787812), "Urls": [], "Priority": 2}, Length: 132
6. Result of using JsonConvert deserialization: Userid:1,username: Li Gang, createdate:1981-3-16 0:20:12,priority:belownormal
7. Using JsonConvert Serialization results: {"UserId": 1, "UserName": "Zhou Gong", "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 of deserialization using LINQ to JSON: ["Http://office.jb51.net", Http://www.jb51.net/web]

Summary: You can see from the above example that the Newtonsoft class library provides a more flexible way of JSON serialization and deserialization, and that in actual development the Duke has been using Newtonsoft as the alternative to JSON serialization and deserialization.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.