Asp.net JSON serialization and deserialization instructions

Source: Internet
Author: User
Tags string to json

In. net JSON serialization and deserialization, we can use the DataContractJsonSerializer class to serialize type instances. I will introduce them in detail.

Serialize and deserialize JSON data

You can use the DataContractJsonSerializer class to serialize a type instance to a JSON string and deserialize the JSON string to a type instance. DataContractJsonSerializer in System. runtime. serialization. in the Json namespace ,. NET Framework 3.5 is included in System. serviceModel. web. dll, you need to add a reference to it ;. NET Framework 4 in the System. runtime. serialization.


Method 1: introduce the System. Web. Script. Serialization namespace and use the JavaScriptSerializer class to implement simple Serialization class: Personnel

 

The Code is as follows: Copy code
Public class Personnel
{
Public int Id {get; set ;}
Public string Name {get; set ;}
}

Execute serialization deserialization:

The Code is as follows: Copy code

Protected void Page_Load (object sender, EventArgs e)
{
Personnel personnel = new Personnel ();
Personnel. Id = 1;
Personnel. Name = "";

JavaScriptSerializer jsonSerializer = new JavaScriptSerializer ();
// Execute serialization
String r1 = jsonSerializer. Serialize (personnel );

// Execute deserialization
Personnel _ Personnel = jsonSerializer. Deserialize <Personnel> (r1 );
}


 

R1 output result: {"Id": 1, "Name": ""}
You can use the ScriptIgnore attribute to mark public or public fields that are not serialized.

The Code is as follows: Copy code
Public class Personnel
{
[ScriptIgnore]
Public int Id {get; set ;}
Public string Name {get; set ;}
}

R1 output result: {"Name": ""}

Method 2: introduce the System. Runtime. Serialization. Json namespace and use the DataContractJsonSerializer class for Serialization.

Serialization class: People

The Code is as follows: Copy code

 

Public class People
{
Public int Id {get; set ;}
Public string Name {get; set ;}
}

Execute serialization deserialization

The Code is as follows: Copy code

Protected void Page_Load (object sender, EventArgs e)
{
People people = new People ();
People. Id = 1;
People. Name = "";


DataContractJsonSerializer json = new DataContractJsonSerializer (people. GetType ());
String szJson = "";
// Serialization
Using (MemoryStream stream = new MemoryStream ())
{
Json. WriteObject (stream, people );
SzJson = Encoding. UTF8.GetString (stream. ToArray ());
}
// Deserialization
Using (MemoryStream MS = new MemoryStream (Encoding. UTF8.GetBytes (szJson )))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer (typeof (People ));
People _ people = (People) serializer. ReadObject (MS );
}
}


 

SzJson output result: {"Id": 1, "Name": ""}

You can use IgnoreDataMember to specify that the member is not part of the Data Protocol and is not serialized. DataMember: defines the serialization attribute parameters. Fields marked with the DataMember attribute must use the DataContract tag class. Otherwise, the DataMember tag does not work.

The Code is as follows: Copy code

 

[DataContract]
Public class People
{
[DataMember (Name = "id")]
Public int Id {get; set ;}
[IgnoreDataMember]
Public string Name {get; set ;}
}

Output result: {"id": 1}

Processing of JSON serialization and deserialization Date and Time
JSON format does not support date and time. The DateTime value is displayed as a JSON string in the format of "/Date (700000 + 0500)/", where the first number (700000 In the example provided) it is the number of milliseconds that have elapsed since midnight, January 1, January 1, 1970 by normal time (non-timeout. This number can be a negative number to indicate the previous time. The example contains "+ 0500", which indicates that the time belongs to the Local type, that is, it should be converted to the Local time zone during deserialization. If this part does not exist, the time is deserialized to Utc.
Modify the Person class and add LastLoginTime:

The Code is as follows: Copy code
Public class Person
{
Public string Name {get; set ;}
Public int Age {get; set ;}
Public DateTime LastLoginTime {get; set ;}
}
Person p = new Person ();
P. Name = "James ";
P. Age = 28;
P. LastLoginTime = DateTime. Now;
String jsonString = JsonHelper. JsonSerializer <Person> (p );

Serialization result:
{"Age": 28, "LastLoginTime": "/Date (1294499956278 + 0800)/", "Name": "James "}
1. Use a regular expression to replace the regular expression in the background. Modify JsonHelper:

The Code is as follows: Copy code

Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Runtime. Serialization. Json;
Using System. IO;
Using System. Text;
Using System. Text. RegularExpressions;
/// <Summary>
/// JSON serialization and deserialization helper class
/// </Summary>
Public class JsonHelper
{
/// <Summary>
/// JSON serialization
/// </Summary>
Public static string JsonSerializer <T> (T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (T ));
MemoryStream MS = new MemoryStream ();
Ser. WriteObject (MS, t );
String jsonString = Encoding. UTF8.GetString (ms. ToArray ());
Ms. Close ();
// Replace the Json Date string
String p = @ "\/Date (d +) + d + )\/";
MatchEvaluator matchEvaluator = new MatchEvaluator (ConvertJsonDateToDateString );
Regex reg = new Regex (p );
JsonString = reg. Replace (jsonString, matchEvaluator );
Return jsonString;
}
/// <Summary>
/// JSON deserialization
/// </Summary>
Public static T JsonDeserialize <T> (string jsonString)
{
// Convert the string in the format of "yyyy-MM-dd HH: mm: ss" to "/Date (1294499956278 + 0800 )/".
String p = @ "d {4}-d {2}-d {2} sd {2}: d {2}: d {2 }";
MatchEvaluator matchEvaluator = new MatchEvaluator (ConvertDateStringToJsonDate );
Regex reg = new Regex (p );
JsonString = reg. Replace (jsonString, matchEvaluator );
DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (T ));
MemoryStream MS = new MemoryStream (Encoding. UTF8.GetBytes (jsonString ));
T obj = (T) ser. ReadObject (MS );
Return obj;
}
/// <Summary>
/// Convert the Json serialization time from/Date (1294499956278 + 0800) to a string
/// </Summary>
Private static string ConvertJsonDateToDateString (Match m)
{
String result = string. Empty;
DateTime dt = new DateTime (1970, 1, 1 );
Dt = dt. AddMilliseconds (long. Parse (m. Groups [1]. Value ));
Dt = dt. ToLocalTime ();
Result = dt. ToString ("yyyy-MM-dd HH: mm: ss ");
Return result;
}
/// <Summary>
/// Convert the time string to Json time
/// </Summary>
Private static string ConvertDateStringToJsonDate (Match m)
{
String result = string. Empty;
DateTime dt = DateTime. Parse (m. Groups [0]. Value );
Dt = dt. ToUniversalTime ();
TimeSpan ts = dt-DateTime. Parse ("1970-01-01 ");
Result = string. Format ("\/Date ({0} + 0800) \/", ts. TotalMilliseconds );
Return result;
}
}

Serialization Demo:

The Code is as follows: Copy code
Person p = new Person ();
P. Name = "James ";
P. Age = 28;
P. LastLoginTime = DateTime. Now;
String jsonString = JsonHelper. JsonSerializer <Person> (p );

Running result:

The Code is as follows: Copy code
{"Age": 28, "LastLoginTime": "01:00:56", "Name": "James "}
Deserialization Demo:
String json = "{" Age ": 28," LastLoginTime ":" 00:30:00 "," Name ":" James "}";
P = JsonHelper. JsonDeserialize <Person> (json );

Related Article

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.