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