將JSON字串反序列化為指定的.NET物件型別
阿新 • • 發佈:2019-10-25
前言:
關於將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"]; 輸出為:操作成功
&n