序列化生成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)
序列化生成JSON数据
热推产品
- ActiveReport... 强大的.NET报表设计、浏览、打印、转换控件,可以同时用于WindowsForms谀坔攀戀Forms平台下......
- AnyChart AnyChart使你可以创建出绚丽的交互式的Flash和HTML5的图表和仪表控件。可以用于仪表盘的创......
推荐产品