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

时间:2022-03-30 19:44:06

【1】首先我们根据创建一个json字符转

string json = @"[{‘phantom‘:true,‘id‘:‘20130717001‘,‘data‘:{‘MID‘:1019,‘Name‘:‘aaccccc‘,‘Des‘:‘cc‘,‘Disable‘:‘启用‘,‘Remark‘:‘cccc‘}}]";

【2】首先我们根据创建一个json字符转

我们根据字符串的数据结构定义两个类:

  public class Info
        {
            public string phantom { get; set; }
            public string id { get; set; }
            public data data { get; set; }
        }

  public class data
        {
            public int MID { get; set; }
            public string Name { get; set; }
            public string Des { get; set; }
            public string Disable { get; set; }
            public string Remark { get; set; }
        }

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

  static void Main(string[] args)
        {
            string json = @"[{‘phantom‘:true,‘id‘:‘20130717001‘,‘data‘:{‘MID‘:1019,‘Name‘:‘aaccccc‘,‘Des‘:‘cc‘,‘Disable‘:‘启用‘,‘Remark‘:‘cccc‘}}]";
            List<Info> jobInfoList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Info>>(json);

            foreach (Info jobInfo in jobInfoList)
            {
                Console.WriteLine("UserName:" + jobInfo.id);
                Console.WriteLine("UserName:" + jobInfo.data.MID);
            }
        }

运行结果如下:

UserName:20130717001
UserName:1019

附加,如相同结构带数组,,则使用递归遍历;

【4】全部完整代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JsonProcess
{
    class Program
    {
        public class Info
        {
            public string phantom { get; set; }
            public string id { get; set; }
            public data data { get; set; }
        }

        public class data
        {
            public int MID { get; set; }
            public string Name { get; set; }
            public string Des { get; set; }
            public string Disable { get; set; }
            public string Remark { get; set; }
        }
        static void Main(string[] args)
        {
            string json = @"[{‘phantom‘:true,‘id‘:‘20130717001‘,‘data‘:{‘MID‘:1019,‘Name‘:‘aaccccc‘,‘Des‘:‘cc‘,‘Disable‘:‘启用‘,‘Remark‘:‘cccc‘}}]";
            List<Info> jobInfoList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Info>>(json);

            foreach (Info jobInfo in jobInfoList)
            {
                Console.WriteLine("UserName:" + jobInfo.id);
                Console.WriteLine("UserName:" + jobInfo.data.MID);
            }
        }
    }
}