.net实体类与json互相转换方法汇总

这次给大家带来.net实体类与json互相转换方法汇总,.net实体类与json互相转换的注意事项有哪些,下面就是实战案例,一起来看一下。

.net实体类与json相互转换时,注意要点:

1.jsonhelp编写时候添加的引用。System.Runtime.Serialization.Json; 
2.实体类需声明为public 

jsonhelp代码: 

  1. 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 // } /// /// 把对象序列化 JSON 字符串 /// /// 对象类型 /// 对象实体 /// JSON字符串 public static string GetJson(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; } } /// /// 把JSON字符串还原为对象 /// /// 对象类型 /// JSON字符串 /// 对象实体 public static T ParseFormJson(string szJson) { T obj = Activator.CreateInstance(); using (MemoryStream ms = new MemoryStream (Encoding.UTF8.GetBytes(szJson))) { DataContractJsonSerializer dcj = new DataContractJsonSerializer(typeof(T)); return (T)dcj.ReadObject(ms); } } }}

登录后复制

实体类代码: 

  1. 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; } }}

登录后复制

控制台应用程序测试代码: 

  1. 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 tlist = new List(); tlist.Add(t1); tlist.Add(t2); tlist.Add(t3); Console.WriteLine(JsonHelp.GetJson<List>(tlist)); // Console.ReadKey(); //json转实体类 List tl = JsonHelp.ParseFormJson <List>(JsonHelp.GetJson<List>(tlist)); Console.WriteLine(tl.Count); Console.WriteLine(tl[0].Name); Console.ReadKey(); } }}

登录后复制

相信看了本文案例你已经掌握了方法,更多精彩请关注【创想鸟】其它相关文章!

推荐阅读:

jQuery做出垂直半透明手风琴效果

jquery实现导航菜单鼠标提示功能

以上就是.net实体类与json互相转换方法汇总的详细内容,更多请关注【创想鸟】其它相关文章!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

点点赞赏,手留余香

给TA打赏
共0人
还没有人赞赏,快来当第一个赞赏的人吧!
    编程技术

    Jquery解析Json字符串与Json数组方法详解

    2025-3-8 11:57:25

    编程技术

    JS操作JSON有哪些方法

    2025-3-8 11:57:31

    0 条回复 A文章作者 M管理员
    欢迎您,新朋友,感谢参与互动!
      暂无讨论,说说你的看法吧
    个人中心
    购物车
    优惠劵
    今日签到
    私信列表
    搜索