首先創建實體類 1 public class MacState 2 { 3 /// <summary> 4 /// 請求狀態 5 /// </summary> 6 public string success { get; set; } 7 /// <summary> 8 /// 錯誤信息 9 /// ...
首先創建實體類
1 public class MacState 2 { 3 /// <summary> 4 /// 請求狀態 5 /// </summary> 6 public string success { get; set; } 7 /// <summary> 8 /// 錯誤信息 9 /// </summary> 10 public string msg { get; set; } 11 public List<MacStateData> data { get; set; } 12 public List<YZ> YZ { get; set; } 13 } 14 15 public class MacStateData { 16 /// <summary> 17 /// 設備名稱 18 /// </summary> 19 public string macName { get; set; } 20 /// <summary> 21 /// 運行狀態 運行停止(1/0) 22 /// </summary> 23 public string state { get; set; } 24 25 } 26 27 public class YZ { 28 /// <summary> 29 /// 姓名 30 /// </summary> 31 public string mName { get; set; } 32 /// <summary> 33 /// 年齡 34 /// </summary> 35 public string AGE { get; set; } 36 }
創建完實體類之後跟實體類賦值 這裡用了List存放一組數據
1 //<summary> 2 /// 組裝json數組簡易方法 不用Stringbuilder 實體類 3 /// </summary> 4 public static void GetMacState() { 5 // 6 MacState obj = new MacState(); 7 obj.success = "true"; 8 obj.msg = "未失敗"; 9 //List集合存放對象 10 obj.data = new List<MacStateData>();//實例化json數組 11 for (int i = 0; i < 3; i++) 12 { 13 14 MacStateData objData = new MacStateData(); 15 objData.macName = "su"; 16 objData.state = "121212"; 17 obj.data.Add(objData); //添加JSON數組集合 18 } 19 20 obj.YZ = new List<YZ>();//實例化json數組 21 for (int i = 0; i < 3; i++)//for迴圈多次添加 22 { 23 YZ YZDATA = new YZ(); 24 YZDATA.mName = "張三"; 25 YZDATA.AGE = "13"; 26 obj.YZ.Add(YZDATA); 27 } 28 string res = JsonConvert.SerializeObject(obj); //轉JSON數組,演示用,下麵講方法使用 29 Console.WriteLine(res); 30 Console.Read(); 31 }
然後就大功告成了!!!
本文參考了https://www.cnblogs.com/chenyanbin/ 的博客