關於將JSON字符串反序列化爲指定的.NET對象類型數據常見的場景主要是關於網絡請求接口,獲取到請求成功的響應數據。本篇主要講的的是如何經過使用Newtonsoft.Json中的JsonConvert.DeserializeObject<T>(string value)方法將對應的JSON字符串轉化爲指定的.NET對象類型數據。網絡
以下是一組.NET後臺請求接口成功獲取到的複雜的JSON字符串數據:spa
{ "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字符串格式數據定義對應的對象參數模型:code
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字符串格式數據:blog
{ "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"]; 輸出爲:操做成功