public class infoObject { public String name { get; set; } public String birthday { get; set; } public String id { get; set; } public String email { get; set; }
public infoObject() { name = ""; birthday = ""; id = ""; email = ""; }
public infoObject(String newname, String newbirthday, String newid, String newemail) { name = newname; birthday = newbirthday; id = newid; email = newemail; }
} public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { infoObject info = new infoObject("peng","19920412","342423188209121234","12312@qq.com"); string szJson; //将对象转成字符串 DataContractJsonSerializer json = new DataContractJsonSerializer(info.GetType()); using (MemoryStream stream = new MemoryStream()) { json.WriteObject(stream, info);//把对象填充到流里(关键) szJson = Encoding.UTF8.GetString(stream.ToArray());//按指定格式把流编码成字符串 Response.Write( "对象转成字符串:<br>"+szJson+"<br>"); }
//将字符串转成对象 //infoObject obj = Activator.CreateInstance<infoObject>(); infoObject obj = new infoObject(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); obj=(infoObject)serializer.ReadObject(ms);//将含有字符串的流转成对象 } Response.Write("字符串转对象:"+obj.name + "<br>" + obj.birthday + "<br>" + obj.id + "<br>" + obj.email); } }