ASP.NET自带对象JSON字符串与实体类的转换
程序员文章站
2023-12-11 23:43:58
关于json的更多介绍,请各位自行google了解!如果要我写的话,我也是去google后copy!嘿嘿,一直以来很想学习json,大量的找资料和写demo,总算有点了解!...
关于json的更多介绍,请各位自行google了解!如果要我写的话,我也是去google后copy!嘿嘿,一直以来很想学习json,大量的找资料和写demo,总算有点了解! 切入正题!
还是先封装一个类吧! 这个类网上都可以找到的!有个这个类,一切都将变得简单了,哈哈。
using system; using system.collections.generic; using system.linq; using system.web; using system.runtime.serialization.json; using system.servicemodel.web;///记得引用这个命名空间 using system.io; using system.text; /// <summary> /// summary description for jsonhelper /// </summary> public class jsonhelper { public jsonhelper() { // // todo: add constructor logic here // } /// <summary> /// 把对象序列化 json 字符串 /// </summary> /// <typeparam name="t">对象类型</typeparam> /// <param name="obj">对象实体</param> /// <returns>json字符串</returns> public static string getjson<t>(t obj) { //记住 添加引用 system.servicemodel.web /** * 如果不添加上面的引用,system.runtime.serialization.json; json是出不来的哦 * */ datacontractjsonserializer json = new datacontractjsonserializer(typeof(t)); using (memorystream ms = new memorystream()) { json.writeobject(ms, obj); string szjson = encoding.utf8.getstring(ms.toarray()); return szjson; } } /// <summary> /// 把json字符串还原为对象 /// </summary> /// <typeparam name="t">对象类型</typeparam> /// <param name="szjson">json字符串</param> /// <returns>对象实体</returns> public static t parseformjson<t>(string szjson) { t obj = activator.createinstance<t>(); using (memorystream ms = new memorystream (encoding.utf8.getbytes(szjson))) { datacontractjsonserializer dcj = new datacontractjsonserializer(typeof(t)); return (t)dcj.readobject(ms); } } }
测试实体类:
public class testdata { public testdata() { } public int id { get; set; } public string name { get; set; } public string sex { get; set; } }
测试页面:
<%@ page language="c#" %> <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <script runat="server"> protected void page_load(object sender, eventargs e) { string jsonstr = string.empty; list<testdata> tds = new list<testdata>(); //测试数据 for (int i = 1; i < 4; i++) { tds.add(new testdata() { id = i, name = "jinho" + i, sex = "male" }); } //把一个list转换为json字符串 jsonstr = jsonhelper.getjson<list<testdata>>(tds); response.write(jsonstr); this.page.clientscript.registerstartupscript(this.gettype(), "json", "getjson(" + jsonstr + ");", true); } </script> <script type="text/javascript"> function getjson(jsonstr) { //使用eval函数 var json = eval(jsonstr); //因为上面为list集合 for (var i = 0; i < json.length; i++) { alert(json[i].id + "name:" + json[i].name); } } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> </div> </form> </body> </html>
关于json字符串转换为实体请各位自己测试吧!只要有上面那个jsonhelper 类,一切都好办!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。