C#中解析JSON数据,并获取到其中的值

时间:2022-02-18 22:55:04

1.应需求创建一个Json字符串

  string json = "[{'Name':'张三','age':'20','Data':{'ID':100,'heigh':'180','weight':'90'}}]";

2.根据字符串的数据结构定义两个类:

  public class User
        {
            public string Name{ get; set; }
            public string age{ get; set; }
            public data Data{ get; set; }
        }

  public class Data
        {
            public int ID{ get; set; }
            public string heigh{ get; set; }
            public string weight{ get; set; }
        }

3.再Main函数中进行操作,如下Main函数:

  static void Main(string[] args)
        {
          string json = "[{'Name':'张三','age':'20','Data':{'ID':100,'heigh':'180','weight':'90'}}]";
            List<User> jobInfoList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<User>>(json);

foreach (Info jobInfo in jobInfoList)
            {
                Console.WriteLine("UserName:" + jobInfo.Name);
                Console.WriteLine("UserName:" + jobInfo.Data.ID);
            }
        }

  public class User
        {
            public string Name{ get; set; }
            public string age{ get; set; }
            public data Data{ get; set; }
        }

  public class Data
        {
            public int ID{ get; set; }
            public string heigh{ get; set; }
            public string weight{ get; set; }
        }