C# Newtonsoft.Json对joson序列化
1.添加Newtonsoft.Json的包。
2.json样例分析(json----->class)
情况A
{ "code": 200, "message": "操作成功", "data": { "consumerId": "XX" }, "success": true }
解析
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { /// <summary> /// 设备 /// </summary> public class Consumer { /// <summary> /// 编码 /// </summary> public string code { set; get; } /// <summary> /// 消息 /// </summary> public string message { set; get; } /// <summary> /// 设备ID /// </summary> public class data { public string consumerId { set; get; } } public string success { set; get; } } public class Consumer_data { public string consumerId { set; get; } } static void Main(string[] args) { string JsonStr = "";//对应的josn JObject jsonObj = JObject.Parse(JsonStr);//string -->>josn对象 Consumer obj = JsonConvert.DeserializeObject<Consumer>(jsonObj.ToString()); string code = obj.code;//编码 string message = obj.message;//消息
Consumer_data Id = JsonConvert.DeserializeObject<Consumer_data>(jsonObj["data"].ToString());//(jsonObj["data"]截取data对象 string consumerId = Id.consumerId;//设备id } } }
情况B
{ "code": 200, "message": "操作成功", "data": [ { "Name": "设备A", "content": "{\"State\":\"运行\",\"NO\":\"A1\"}" }, { "Name": "设备B", "content": "{\"State\":\"关机\",\"NO\":\"A2\"}" } ], "success": true }
解析
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { /// <summary> /// 设备 /// </summary> public class Consumer { /// <summary> /// 编码 /// </summary> public string code { set; get; } /// <summary> /// 消息 /// </summary> public string message { set; get; } /// <summary> /// 设备情况 /// </summary> public class data { public string State { set; get; } public string NO { set; get; } } public string success { set; get; } } public class Consumer_data { public string State { set; get; } public string NO { set; get; } } static void Main(string[] args) { string JsonStr = "";//对应的josn JObject jsonObj = JObject.Parse(JsonStr);//string -->>josn对象 Consumer obj = JsonConvert.DeserializeObject<Consumer>(jsonObj.ToString()); string code = obj.code;//编码 string message = obj.message;//消息 string success = obj.success;//是否可以 List<Consumer_data> list = new List<Consumer_data>(); string ContentString = jsonObj["data"].ToString();//jsonObj["data"]截取data对象 JArray jlist = JArray.Parse(ContentString); foreach (var jsonitem in jlist) { JObject job = (JObject)jsonitem; Consumer_data content = JsonConvert.DeserializeObject<Consumer_data>(job["data"].ToString()); list.Add(content); } } } }