这次给大家带来.net实体类与json互相转换方法汇总,.net实体类与json互相转换的注意事项有哪些,下面就是实战案例,一起来看一下。
.net实体类与json相互转换时,注意要点:
1.jsonhelp编写时候添加的引用。system.runtime.serialization.json;
2.实体类需声明为public
jsonhelp代码:
using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;
using system.runtime.serialization.json;
using system.io;
namespace jsontest
{
class jsonhelp
{
public jsonhelp()
{
//
// 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);
}
}
}
}
实体类代码:
using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;
namespace jsontest
{
public class testdata
{
public testdata()
{
}
public int id { get; set; }
public string name { get; set; }
public string sex { get; set; }
}
}
控制台应用程序测试代码:
using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;
namespace jsontest
{
class program
{
static void main(string[] args)
{
//实体类转json
testdata t1 = new testdata();
t1.id = 1;
t1.name = 001姓名;
t1.sex = 男;
testdata t2 = new testdata();
t2.id = 2;
t2.name = 002姓名;
t2.sex = 男;
testdata t3 = new testdata();
t3.id = 3;
t3.name = 003姓名;
t3.sex = 男;
list<testdata> tlist = new list<testdata>();
tlist.add(t1);
tlist.add(t2);
tlist.add(t3);
console.writeline(jsonhelp.getjson(tlist));
// console.readkey();
//json转实体类
list<testdata> tl = jsonhelp.parseformjson (jsonhelp.getjson(tlist));
console.writeline(tl.count);
console.writeline(tl[0].name);
console.readkey();
}
}
}
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
jquery做出垂直半透明手风琴效果
jquery实现导航菜单鼠标提示功能
以上就是.net实体类与json互相转换方法汇总的详细内容。