首页 > 解决方案 > 尝试使用模型反序列化时出现 Newtonsoft.Json.JsonSerializationException 问题

问题描述

m 试图反序列化一个 Json 文件,使用这个类作为模型:

using CsQuery.StringScanner.Patterns;
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Text;

namespace Test_Api
{
    public class Metric
    {
        public string __name__ { get; set; }
        public string instance { get; set; }
        public string job { get; set; }

    }
    public class Result
    {
        public Metric metric { get; set; }
        public IList<Lucene.Net.Support.Number> value { get; set; }

    }
    public class Data
    {
        public string resultType { get; set; }
        public IList<Result> result { get; set; }

    }
    public class Application
    {
        public string status { get; set; }
        public Data data { get; set; }

    }
}

我的 Program.cs 是:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using QuickType;
namespace Test_Api
{
    class Program
    {
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            List<Application> DataG = new List<Application>();
            using (var httpClient = new HttpClient())
            {
                using (var response = await httpClient.GetAsync("http://localhost:9090/api/v1/query?query=go_memstats_gc_cpu_fraction"))
                {
                    string apiResponse = await response.Content.ReadAsStringAsync();
                    DataG = JsonConvert.DeserializeObject<List<Application>>(apiResponse);
                }
            }
            Console.WriteLine(DataG);
        }

    }
}

它一直给我这个错误:

Newtonsoft.Json.JsonSerializationException:'无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.List`1[Test_Api.Application]',因为该类型需要 JSON 数组(例如 [1,2,3])正确反序列化。

我想知道是否有一种使用特定模型反序列化 json 事物的标准方法,任何帮助将不胜感激,请客气,我是新手。

编辑: 我想从中获取值的 Json 是:

{
    "status": "success",
    "data": {
        "resultType": "vector",
        "result": [
            {
                "metric": {
                    "__name__": "process_cpu_seconds_total",
                    "instance": "localhost:9090",
                    "job": "prometheus"
                },
                "value": [
                    1545222126.353,
                    "0.615464"
                ]
            }
        ]
    }
}

标签: c#jsonrestapiasp.net-core

解决方案


你需要使用

var result = JsonConvert.DeserializeObject<Application>(apiResponse);

您的 Json 返回 的单个实例Application,而您尝试按照List<Application>OP 中的代码将 Json 反序列化为 a 。这是错误的原因。


推荐阅读