在日常开发中经常需要Json解析,所以这里简单记录下

引用Newtonsoft.Json类库

NuGet搜索Newtonsoft.Json并安装(不用搜,打开NuGet管理器第一个就是)

接着开头添加using Newtonsoft.Json;

本文测试用Json

{
    "RequestId": "AFD9185D-4966-476C-8BED-5DABB7A0AFB5",
    "Data": {
        "Elements": [
            {
                "Score": "0.7757113575935364",
                "Box": [
                    "29.702007293701172",
                    "33.544498443603516",
                    "411.5091552734375",
                    "227.99440002441406"
                ],
                "Name": "桔子"
            }
        ]
    }
}

压缩转义一下(网上一堆工具),方便演示

{\"RequestId\":\"AFD9185D-4966-476C-8BED-5DABB7A0AFB5\",\"Data\":{\"Elements\":[{\"Score\":\"0.7757113575935364\",\"Box\":[\"29.702007293701172\",\"33.544498443603516\",\"411.5091552734375\",\"227.99440002441406\"],\"Name\":\"桔子\"}]}}

将Json转化为实体类

这里推荐一个好工具:http://json2csharp.chahuo.com/

转化为C#实体类之后如下(有时候不能直接用,看着改):

public class Elements {
    public string Score  { get; set; }
    public List<String> Box { get; set; }
    public string Name  { get; set; }
}

public class Data {
    public List<Elements> Elements { get; set; }
}

public class RootObject {
    public string RequestId  { get; set; }
    public Data Data { get; set; }
}

解析Json

将实体类引入到Program.cs

反序列化Json:

RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(jsonStr);

获得数据:

Console.WriteLine(rootObject.Data.Elements[0].Name);

完整代码——Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string jsonStr = "{\"RequestId\":\"AFD9185D-4966-476C-8BED-5DABB7A0AFB5\",\"Data\":{\"Elements\":[{\"Score\":\"0.7757113575935364\",\"Box\":[\"29.702007293701172\",\"33.544498443603516\",\"411.5091552734375\",\"227.99440002441406\"],\"Name\":\"桔子\"}]}}";
            RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(jsonStr);
            Console.WriteLine(rootObject.Data.Elements[0].Name);

        }
    }


    public class Elements
    {
        public string Score { get; set; }
        public List<String> Box { get; set; }
        public string Name { get; set; }
    }

    public class Data
    {
        public List<Elements> Elements { get; set; }
    }

    public class RootObject
    {
        public string RequestId { get; set; }
        public Data Data { get; set; }
    }
}
最后修改:2021 年 04 月 14 日
如果觉得我的文章对你有用,请随意赞赏