.Net 中关于序列化和反序列化Json的方法
来源:互联网 发布:自学程序员的步骤 编辑:程序博客网 时间:2024/06/08 09:49
.Net SDK中关于序列化和反序列化Json的方法
项目中遇到和服务端交互时需要传递数据包为json格式的包,所以在服务端和SDK中都需要对json进行解析和组合的操作, 并且对一些复杂结构的json格式的解析和序列化比较麻烦, 幸好,.Net提供一些方法的库可以帮助我们完成一些工作,下面介绍一下利用.Net中的Newtonsoft.Json.dll库对json进行序列化和反序列化操作。
Json操库的介绍:
.NET自身有System.Runtime.Serialization.dll与System.Web.Extensions.dll,使用这两个DLL可以把对象序列化和反序列化成Json数据。
也可以使用第三方的Newtonsoft.Json.dll来操作Json数据,使用它会更方便的操作Json数据,其功能也跟强一些。
但是:使用System.Web.Extensions.dll的限序列化, 一般不怎么使用,因为:要使用System.Web.Extensions.dll必须是在Web项目中,只有在Web项目中才能引用此DLL。
并且前两种方式在项目中也没怎么用过,所以主要介绍第三种方式,利用Newtonsoft.Json.dll来操作json.
首先要将该动态库加入到项目中,在.Net项目中直接添加引用即可。
1、 序列化
1.1 一般格式
要想得到一个最正常的以下格式的json结构:
{ "status": "create", "subject": "envelope demo,sent recipients", "message": "demo sign...", "senderId": "0638bb2d-74c1-494b-ba50-e7caaf09ca77", "projectKey": "10000006"}
以下方法实现:
直接给json逐个字段构造
public class Json { JObject json { get; set; } public string GetJson() { this.json = new JObject(); this.json["status"] = "create"; this.json["subject"] = "envelope demo"; this.json["message"] = "demo"; this.json["senderId"] = "0638bb2d"; this.json["projectKey"] = "10000006"; return this.json.ToString(); }}
返回结果:
Json objjson = new Json(); string json = objjson.GetJson();
返回json为上面我们指定格式的字符串。
1.2 对象
将对象直接格式化为json字符串。
Eg:public class Json
{
public string status { set; get; }
public string subject { set; get; }
public string message { set; get; }
public string senderId { set; get; }
public string projectKey { set; get; }
}
直接序列化:
Json objjson = new Json();
objjson.status = "create";………
string jsonData = JsonConvert.SerializeObject(objjson);
返回结果和上面一样的字符串, 前提是先给对象赋值, 如果不复制返回下面内容:
{"status":null,"subject":null,"message":null,"senderId":null,"projectKey":null}
注意:json key的名称和对象中的一样。 按照这样的逻辑,发序列化对象的名称要和json一样才能将其反序列化出来。
1.3 数组
使用List构造数组进行序列化,首先定义对象,构造格式;
如果想得到下列格式的json:
"documents": [ { "name": "demo.pdf", "fileKey": "$08ac5875-345a-4339-a6a3-fca02a85ba92$180375027", "templateRequired": "false", "templateId": "", "type": "pdf" }, { "name": "demo2.pdf", "fileKey": "$08ac5875-325a-4339-a6a3-fca02a85ba92$180375046", "templateRequired": "false", "templateId": "", "type": "pdf" } ]
则使用对象序列化;
public class DocInfo { public string Name { set; get; } public string FileKey { set; get; } public string TemplateRequired { set; get; } public string TemplateId { set; get; } public string Type { set; get; } }Void Main(){List<DocInfo> list = new List<DocInfo>(); DocInfo info = new DocInfo(); info.Name = "demo.pdf"; info.FileKey = "$08ac5875 - 325a - 4339 - a6a3 - fca02a85ba92$180375046"; info.TemplateRequired = "false"; info.Type = "pdf"; list.Add(info); info.Name = "demo2.pdf"; info.FileKey = "$08ac5875-325a-4339-a6a3-fca02a85ba92$180375046"; list.Add(info);string jsonStr = JsonConvert.SerializeObject(list);//将对象转换成json存储this.Json["documents"] = JArray.Parse(strRecipients);}
得到的便是以上我们定义的结构了;
1.4 嵌套格式
对于嵌套格式,通常都是由以上的三点的简单格式组成的,将其拆分合成后,组合到一起便可以了,或者定义对应结构的对象, 直接进行序列化即可完成。
2、 反序列化
2.1一般格式
解析如下格式:
string jsonText = "{\"zone\":\"海淀\",\"zone_en\":\"haidian\"}";void main(){JObject jo = JObject.Parse(jsonData);或者JObject jo = (JObject)JsonConvert.DeserializeObject(jsonData);string zone = jo["zone"].ToString();string zone_en = jo["zone_en"].ToString();}
2.2对象
解析如下格式json:
string strJson = { "data": { "signedFileKey":"$f605cb35-2c4e-41f3-a16a-3eee41b39556$1638665701", "signLogId": "02f1a5ff-d3e4-48df-9684-aed92081d6a7" }, "errCode": 0, "errShow": true, "msg": ""}定义一个对象:namespace JsonOper{public class JSON{ public int ErrCode { get; set; } public bool ErrShow { get; set; } public string Msg { get; set; } public DATA data { set; get; }}public class DATA{ public string SignedFileKey { set; get; } public string SignLogId { set; get; }}}JSON jo = JsonConvert.DeserializeObject<JSON>(strJson);
得到的结果便是一个反序列化好了的对象。
注:定义发序列化对象时,要对象json格式定义, 比如有嵌套, 对象格式也要嵌套, 否则无法反序列化成功, 并且定义时,对象中的变量名称要和json中一直, 大小写没关系。
Eg:以上例子中
"errCode": 0,"errShow": true,"msg": ""
定义时可以定义为:
public class JSON{ public int ErrCode { get; set; } public bool ErrShow { get; set; } public string Msg { get; set; }}
因为反序列化是对属性的。 对象默认有一个小写字母开头的属性;总之这个无伤大雅。 一般首字母大写。
2.3数组
说来奇怪,项目中反序列化一个嵌套格式的json,定义了一个嵌套对象,但是竟然不成功, 一怒之下, 换了一种方法, 因为懒的去查什么原因了。
大体如下:
Json:{ "data": { "envelope": { "status": "Sent", "subject": "envelope demo,sent recipients", "message": "demo sign...", "redirectUrl": "http://xxxx.xxx.xxx/xxx", "notifyUrl": "http://xxxx.xxx.xxx/xxx", "senderId": "0638bb2d-74c1-494b-ba50-e7caaf09ca77", "senderName": "Wesley", "sentDateTime": "2017-08-17T06:55:48.6800000Z", "document": { "docUUID": "07ec608d-6840-4856-b599-783843efcdb6", "signFileKey": "08ec608d-6840-4856-b599-783843efcdb6", "name": "demo.pdf", "templateRequired": "false", "templateId": "", "type": "Pdf" }, "recipients": [{ "recipientId": "07ec608d-6840-4856-b599-783843efcdb6", "flowId": "44ec608d-6840-4856-b599-783843efcbc6", "currentHandlerFlag":"true", "licenseType": "IDCard", "licenseID": "362389xxxxxxxx8766", "routingOrder": "1", "type": "Signers", "email": "123@123.com", "phone": "12389978998", "accountUniqueId": "23344555", "departmentId": "dkdksjj", "departmentName": "department A", "autoSignFlag": "N", "signType": "PatientSign", "recipientType": "Personal", "status": "Signed", "predefineSign": { "posType":"Free", "key": "", "posX": 0, "posY": 0, "posPage": "1" } }, { "recipientId": "07ec608d-6840-4856-b599-783843efcdb6", "flowId": "", "currentHandlerFlag":"false", "licenseType": "IDCard", "licenseID": "362389xxxxxxxx8766", "routingOrder": "2", "type": "CC", "email": "123@123.com", "phone": "12389978998", "accountUniqueId": "23344555", "departmentId": "dkdksjj", "departmentName": "department B", "autoSignFlag": "N", "signType": "PatientSign", "recipientType": "Personal", "status": "Sent", "predefineSign": { "posType":"Free", "key": "", "posX": 0, "posY": 0, "posPage": "1" } }] }, "errCode": 0, "errShow": true, "msg": "" }}
以上结构中,有嵌套对象, 有嵌套数组, 数组中嵌套对象。
解析方法:
定义对象:
namespace xxxx{ public class EnvelopInfoResult : Result { public EnvelopeDataResult EnvelopData { set; get; }} public class EnvelopeDataResult { public string Status { set; get; } public String SubJect { set; get; } public String Message { set; get; } public String SenderId { set; get; } public String SenderName { set; get; } public string SentDateTime { set; get; } public DocInfoResult Document { set; get; } public List<RecipientsInfoPersonResult> PersonRecipientsInfos { set; get; } public List<RecipientsInfoDepartResult> DepartRecipientsInfos { set; get; } } public class DocInfoResult { public string DocUUID { set; get; } public string SignFileKey { set; get; } public string Name { set; get; } public string TemplateRequired { set; get; } public string TemplateId { set; get; } public string Type { set; get; } } public class PositionBeanResult { public string posType { set; get; } public string PosPage { set; get; } public string Key { get; set; } public float PosX { get; set; } public float PosY { get; set; } public float Width { get; set; } } public class RecipientsReturn : Recipients{ public string licenseType { set; get; } public string licenseID { set; get; } public string email { set; get; } public string phone { set; get; } public string accountUniqueId { set; get; } public string recipientType { set; get; } public string departmentId { set; get; } public string autoSignFlag { set; get; } public string signType { set; get; } public string ReciepientId { set; get; } public string FlowId { set; get; } public string CurrentHanderFlag { set; get; } public string DepartmentName { set; get; } public string Status { set; get; } }}
将json解析到以上定义对象中:
JObject json = (JObject)JsonConvert.DeserializeObject(strJson);//转换为对象 EnvelopInfoResult result = EnvelopInfoResult.ParseJson(json); public static EnvelopInfoResult ParseJson(JObject json) { EnvelopInfoResult res = new EnvelopInfoResult(); EnvelopeDataResult data = new EnvelopeDataResult(); res.EnvelopData = data; res.ErrCode = int.Parse(json["errCode"].ToString()); res.ErrShow = Convert.ToBoolean(json["errShow"].ToString()); res.Msg = json["msg"].ToString(); //Parse obj //转换为对象 var obj = json["data"]["envelope"].ToObject<JObject>(); //获取对应字段值 res.EnvelopData.Status = obj.GetValue("status").ToString(); res.EnvelopData.SubJect = obj.GetValue("subject").ToString(); res.EnvelopData.Message = obj.GetValue("message").ToString(); res.EnvelopData.SenderId = obj.GetValue("senderId").ToString(); res.EnvelopData.SenderName = obj.GetValue("senderName").ToString(); res.EnvelopData.SentDateTime = obj.GetValue("sentDateTime").ToString(); //将document对象直接转换为定义的对象 res.EnvelopData.Document = obj.GetValue("document").ToObject<DocInfoResult>(); // recipients对应的数组部分是一个对象, 获取json将其转换成JArray数组,然后遍历数组获取每个字段对应的值。 string strListJson = obj.GetValue("recipients").ToString(); JArray jar = JArray.Parse(strListJson); foreach (var nobj in jar) { RecipientsReturn rec = nobj.ToObject<RecipientsReturn>(); if ("Personal" == rec.recipientType) { res.EnvelopData.PersonRecipientsInfos = new List<RecipientsInfoPersonResult>(); RecipientsInfoPersonResult Recp = new RecipientsInfoPersonResult(); Recp.ReciepientId = rec.ReciepientId; Recp.FlowId = rec.FlowId; Recp.CurrentHanderFlag = Convert.ToBoolean(rec.CurrentHanderFlag); Recp.licenseType = GetType<LicenseType>(rec.licenseType); Recp.LicenseId = rec.licenseID; Recp.RoutingOrder = rec.routingOrder; Recp.Type = GetType<SendType>(rec.type); Recp.Email = rec.email; Recp.Phone = rec.phone; Recp.AccountUniqueId = rec.accountUniqueId; Recp.SignType = GetType<SignType>(rec.signType); Recp.status = GetType<RecipientStatus>(rec.Status); Recp.PredefineSign = SetPos(rec.predefineSign); res.EnvelopData.PersonRecipientsInfos.Add(Recp); } else { res.EnvelopData.DepartRecipientsInfos = new List<RecipientsInfoDepartResult>(); RecipientsInfoDepartResult Recd = new RecipientsInfoDepartResult(); Recd.RecipientId = rec.ReciepientId; Recd.FlowId = rec.FlowId; Recd.CurrentHandlerFlag = Convert.ToBoolean(rec.CurrentHanderFlag); Recd.RoutingOrder = rec.routingOrder; Recd.AccountUniqueId = rec.accountUniqueId; Recd.DepartmentId = rec.departmentId; Recd.AutoSignFlag = Convert.ToBoolean(rec.autoSignFlag); Recd.status = GetType<RecipientStatus>(rec.Status); Recd.PredefineSign = SetPos(rec.predefineSign); res.EnvelopData.DepartRecipientsInfos.Add(Recd); } } return res; }
好了,打完收工。
- .Net 中关于序列化和反序列化Json的方法
- 关于JSON.NET中对json的序列化和反序列化
- .Net中JSON序列化和反序列化
- .NET进行Json的序列化和反序列化
- 关于Json的序列化和反序列化
- js中json的序列化和反序列化
- .NET Framewok 3.5 中 JSON 序列化和反序列化的简单实现
- .NET Framewok 3.5 中 JSON 序列化和反序列化的简单实现
- .NET Framewok 3.5 中 JSON 序列化和反序列化的简单实现
- .NET Framewok 3.5 中 JSON 序列化和反序列化的简单实现
- .NET Framewok 3.5 中 JSON 序列化和反序列化的简单实现
- .NET Framewok 3.5 中 JSON 序列化和反序列化的简单实现
- .NET Framewok 3.5 中 JSON 序列化和反序列化的简单实现
- ASP.NET中JSON的序列化和反序列化
- ASP.NET中JSON的序列化和反序列化
- ASP.NET中JSON的序列化和反序列化
- ASP.NET中JSON的序列化和反序列化
- ASP.NET中JSON的序列化和反序列化
- jetty servlet容器(转自博客园)
- idea maven项目找不到 mapper.xml sql映射文件问题
- 注释必备
- 如何在Windows下安装numpy?
- tomcat启动报错
- .Net 中关于序列化和反序列化Json的方法
- 分析Hive表和分区的统计信息(Statistics)
- JSP的文件上传方法
- 获取表单提交的信息
- web.xml文件中加载顺序的优先级
- jQuery拖放节点
- Android Studio 版本迁移的配置问题以及 GreenDAO3.0的配置使用
- postgresql触发器
- 城市智能交通发展现状与前景预测