serialize Json with C#
#region Jsonhelper
using System.IO;
using System.Text;
using System.Runtime.Serialization.Json;
public class JsonHelper
{
/// <summary>
/// JSON序列化
/// </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();
return jsonString;
}
/// <summary>
/// JSON反序列化
/// </summary>
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);
return obj;
}
}
#endregion
public partial class trade_in_manage_flist : System.Web.UI.Page
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
Person[] pArr = new Person[] {
new Person() { Age = 5, Name = "zy" } ,
new Person() { Age = 6, Name = "zk" } ,
new Person() { Age = 7, Name = "zx" } ,
new Person() { Age = 8, Name = "zz" } ,
};
string jsonString = JsonHelper.JsonSerializer<Person[]>(pArr);
Response.Write(jsonString);
}
}
using System.IO;
using System.Text;
using System.Runtime.Serialization.Json;
public class JsonHelper
{
/// <summary>
/// JSON序列化
/// </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();
return jsonString;
}
/// <summary>
/// JSON反序列化
/// </summary>
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);
return obj;
}
}
#endregion
public partial class trade_in_manage_flist : System.Web.UI.Page
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
Person[] pArr = new Person[] {
new Person() { Age = 5, Name = "zy" } ,
new Person() { Age = 6, Name = "zk" } ,
new Person() { Age = 7, Name = "zx" } ,
new Person() { Age = 8, Name = "zz" } ,
};
string jsonString = JsonHelper.JsonSerializer<Person[]>(pArr);
Response.Write(jsonString);
}
}
The result string is :
[{"Age":5,"Name":"zy"},{"Age":6,"Name":"zk"},{"Age":7,"Name":"zx"},{"Age":8,"Name":"zz"}]