2020-05-29

组装Json数据的一种简单办法(不用Stringbuilder方法)

组装Json数据的一种简单办法(不用Stringbuilder方法)


首先创建实体类

 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/ 的博客 


No comments:

Post a Comment