[asp]代码库
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Person person = new Person { ID = 1,Name="OutOfMemory.CN" };
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Person));
//序列化json对象
using (var ms = new MemoryStream())
{
jsonSerializer.WriteObject(ms, person);
String json = Encoding.UTF8.GetString(ms.ToArray());
literalJson.Text = json;
}
//反序列化json对象
var jsonText = @"{""id"":2,""name"":""OutOfMemory.CN""}";
using (var ms = new MemoryStream())
{
var buffer = Encoding.UTF8.GetBytes(jsonText);
ms.Write(buffer, 0, buffer.Length);
ms.Seek(0, SeekOrigin.Begin);
var objPerson = (Person)jsonSerializer.ReadObject(ms);
literalPersonInfo.Text = string.Format("person id == {0},person name = {1}", objPerson.ID, objPerson.Name);
}
}
}
}