using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Web.Script.Serialization;
using System.Runtime.Serialization.Json;
/// <summary>
/// json反序列化对象
/// </summary>
public class Nature
{
public string name { get; set; }//属性编号
public string sex { get; set; } //分类编号
}
/// <summary>
/// json反序列化对象
/// </summary>
public class Person
{
public string name { get; set; }//属性编号
public string sex { get; set; } //分类编号
public string age { get; set; } //分类编号
public string tel { get; set; } //分类编号
}
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//复杂的json解析
String json = "[{\"name\":\"zhangsan\",\"sex\":\"男\"},{\"name\":\"李四\",\"sex\":\"男\"},{\"name\":\"张娟\",\"sex\":\"女\"},{\"name\":\"慧娟\",\"sex\":\"女\"}]";
List<Nature> nt = Deserialize<List<Nature>>(json);
if (nt != null && nt.Count > 0)
{
Response.Write("复杂的json反序列化:<br/>");
foreach (Nature dt in nt)//打印集合中的元素
{
Response.Write(dt.name+"<br/>");
}
}
//简单的json解析
String json1 = "{\"name\":\"张三\",\"sex\":\"男\",\"age\":\"25\",\"tel\":\"1301554XXXX\"}";
JavaScriptSerializer js = new JavaScriptSerializer();
Person pe = js.Deserialize<Person>(json1);
Response.Write("<br/>简单的json反序列化:" + pe.name);
Response.Write("<h5>序列化操作</h5>");
Response.Write("<h5>复杂对象序列化</h5>");
List<Nature> list = new List<Nature>()
{
new Nature(){ name="张三", sex="男"},
new Nature(){ name="慧娟", sex="女"}
};
string jsonTxt = JsonSerializer<List<Nature>>(list);
Response.Write(jsonTxt);
Response.Write("<h5>简单对象序列化</h5>");
Person pes = new Person();
pes.name = "姐姐";
pes.sex = "女";
pes.tel = "1301554XXXX";
pes.age = "23";
string json1Txt = JsonSerializer<Person>(pes);
Response.Write(json1Txt);
}
/// <summary>
/// 反序列化json数组
/// </summary>
/// <typeparam name="T">对象</typeparam>
/// <param name="json">json数组</param>
/// <returns></returns>
public T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
return (T)serializer.ReadObject(ms);
}
}
/// <summary>
/// 序列化对象为json
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="t">对象</param>
/// <returns></returns>
public 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;
}
}