失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > .net实体类与json互相转换方法汇总

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

时间:2023-11-15 15:48:56

相关推荐

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

web前端|js教程

javascript,.net,json

web前端-js教程.net实体类与json相互转换时,注意要点:

php array源码,微软为什么要做vscode,ubuntu efi启动,tomcat上传war包,sqlite对象,网页设计z型布局范例,php 三级联动 数据库,百度上传服务器错误,腾讯支付插件,se前端框架,压制爬虫脑,php搜索字符串,seo建站能赚钱,springboot 开涛,phpssc网站源码,网页代码在线压缩,政府网站模板asp,多多返利 后台密码,ecshop 注册页面修改,企业管理系统开源,分类网程序lzw

1.jsonhelp编写时候添加的引用。System.Runtime.Serialization.Json;

2.实体类需声明为public

java swt 学生成绩管理系统源码,ubuntu14商店,爬虫数据入库教程,sqrt()php,珠海推广seolzw

jsonhelp代码:

宠物企业源码,ubuntu签名模块,网络爬虫的类别,吕钢 php,seo内容代码lzw

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字符串 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字符串 /// 对象实体 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); } } }}

实体类代码:

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) {//实体类转jsontestData 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(); } }}

如果觉得《.net实体类与json互相转换方法汇总》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。