前言:
关于将 JSON 字符串反序列化为指定的. NET 对象类型数据常见的场景主要是关于网络请求接口, 获取到请求成功的响应数据. 本篇主要讲的的是如何通过使用 Newtonsoft.JSON 中的 JsonConvert.DeserializeObject<T>(string value) 方法将对应的 JSON 字符串转化为指定的. NET 对象类型数据.
方法一, 在项目中定义对应的对象参数模型, 用于映射反序列化出来的参数 (复杂 JSON 字符串数据推荐使用):
如下是一组. NET 后台请求接口成功获取到的复杂的 JSON 字符串数据:
- {
- "id": "123456",
- "result": {
- "data": {
- "liveToken": "zxcvbnm",
- "liveStatus": 1,
- "liveType": 1,
- "deviceId": "1234567890",
- "channelId": "0",
- "coverUpdate": 30,
- "streams": [{
- "hls": "zxcv.safd",
- "coverUrl": "http://asdaf",
- "streamId": 0
- }],
- "job": [{
- "status": true,
- "period": "always"
- }]
- },
- "code": "0",
- "msg": "操作成功"
- }
- }
根据该组 JSON 字符串格式数据定义对应的对象参数模型:
- public class BindDeviceLiveHttpsResponse
- {
- public BindDeviceLiveHttpsResult result { get; set; }
- public string id { get; set; }
- }
- public class BindDeviceLiveHttpsResult
- {
- public BindDeviceLiveHttpsData data { get; set; }
- public string code { get; set; }
- public string msg { get; set; }
- }
- public class BindDeviceLiveHttpsData
- {
- public string liveToken { get; set; }
- public int liveStatus { get; set; }
- public int liveType { get; set; }
- public string deviceId { get; set; }
- public string channelId { get; set; }
- public int coverUpdate { get; set; }
- public List<BindDeviceLiveHttpsStreams> streams { get; set; }
- public List<BindDeviceLiveHttpsJob> job { get; set; }
- }
- public class BindDeviceLiveHttpsStreams
- {
- public string hls { get; set; }
- public string coverUrl { get; set; }
- public int streamId { get; set; }
- }
- public class BindDeviceLiveHttpsJob
- {
- public bool status { get; set; }
- public string period { get; set; }
- }
通过 JsonConvert.DeserializeObject < 自定义模型 >(string value) 反序列化:
- var resultContext = JsonConvert.DeserializeObject<GetLiveStreamInfoResponse>(JSON 字符串数据);
- // 最后我们可以通过对象点属性名称获取到对应的数据
方法二, 直接将 JSON 字符串格式数据反序列化转化为字典数据 (简单 JSON 字符串数据推荐使用):
如下一组简单的 JSON 字符串格式数据:
- {
- "id": "123456",
- "code": "0",
- "msg": "操作成功"
- }
通过 JsonConvert.DeserializeObject<Dictionary<string, object>>(string value) 方法反序列化为字典数据, 在通过 key 访问对应的 value 的值:
- var resultContext=JsonConvert.DeserializeObject<Dictionary<string, object>>(JSON 格式数据);
- // 获取 msg 的值:
- var msg=resultContext["msg"];
输出为: 操作成功
来源: https://www.cnblogs.com/Can-daydayup/p/11735950.html