C # writes common JSON data for serialization and deserialization

Source: Internet
Author: User

Note: Using JSON serialization and deserialization, you must add a reference System.Runtime.Serialization.

1. The general class code is as follows:

<summary>
JSON serialization and deserialization helper classes
</summary>
public class Jsonhelper
{
<summary>
JSON serialization
</summary>
<typeparam name= "T" ></typeparam>
<param name= "T" ></param>
<returns></returns>
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 ();
return jsonstring;
}

<summary>
JSON deserialization
</summary>
<typeparam name= "T" ></typeparam>
<param name= "Jsonstring" ></param>
<returns></returns>
public static T jsondeserialize<t> (String jsonstring)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (T));
MemoryStream ms = new MemoryStream (Encoding.UTF8.GetBytes (jsonstring));
T obj = (t) ser. ReadObject (MS);
Ms. Close ();
return obj;
}
}

2. Define the calling class, as follows:

<summary>
Defining classes
</summary>
public class Person
{
public string Name {get; set;}
public int Age {get; set;}
}

3. Call serialization and deserialization operations as follows:

Person p = new person ();
P.name = "Chen Lei";
p.age = 29;

Call JSON serialization

String Strjson = Jsonhelper.jsonserializer<person> (p);
Console.WriteLine (Strjson);

Call JSON deserialization
String Strdjson = "{\" age\ ": 28,\" name\ ": \" Chen Lei \ "}";
Person DP = jsonhelper.jsondeserialize<person> (Strdjson);
Console.WriteLine (DP. Name + "," + DP. Age);

C # writes common JSON data for 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.