序列化生成JSON数据
类代码:
C#版本
/// <summary>
/// 反序列化JSON
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
/// <param name="jsonString">JSON字符串</param>
/// <returns></returns>
public static T JsonDeserialize<T>(string strJson)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson));
T objT = (T)ser.ReadObject(ms);
ms.Close();
return objT;
}
/// <summary>
/// 序列化JSON
/// </summary>
/// <typeparam name="T">序列化对象类型</typeparam>
/// <param name="objT">序列化对象</param>
/// <returns></returns>
public static string JsonSerializer<T>(T objT)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, objT);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return jsonString;
}
VB.NET版本
''' <summary>
''' 反序列化JSON数据
''' </summary>
''' <typeparam name="T">返回类型</typeparam>
''' <param name="strJson">JSON字符串</param>
''' <returns></returns>
''' <remarks></remarks>
Private Function JsonDeserialize(Of T)(ByVal strJson As String) As T
Dim ser As New DataContractJsonSerializer(GetType(T))
Dim ms As New MemoryStream(Encoding.UTF8.GetBytes(strJson))
Dim objT As T = ser.ReadObject(ms)
ms.Close()
Return objT
End Function
''' <summary>
''' 序列化生成JSON数据
''' </summary>
''' <typeparam name="T">序列化对象类型</typeparam>
''' <param name="objT">序列化对象</param>
''' <returns></returns>
''' <remarks></remarks>
Private Function JsonSerializer(Of T)(ByVal objT As T) As String
Dim ser As New DataContractJsonSerializer(GetType(T))
Dim ms As New MemoryStream()
ser.WriteObject(ms, objT)
Dim strJson As String = Encoding.UTF8.GetString(ms.ToArray())
ms.Close()
Return strJson
End Function
ASPX 页面调用:
C#版:
Student stu = new Student(1, "小红", "女");
string str = JsonSerializer(stu);
Student stuItem = JsonDeserialize<Student>(str);
VB.NET版:
Dim stu As New Student(1, "张学友", "男")
Dim str As String = JsonSerializer(stu)
Dim itemStu As Student = JsonDeserialize(Of Student)(str)