c# - 尝试使用模型反序列化时出现 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"
]
}
]
}
}
解决方案
你需要使用
var result = JsonConvert.DeserializeObject<Application>(apiResponse);
您的 Json 返回 的单个实例Application
,而您尝试按照List<Application>
OP 中的代码将 Json 反序列化为 a 。这是错误的原因。
推荐阅读
- python-3.x - 将具有随机值的列添加到 pyspark 数据帧
- kotlin - 有没有办法在 Kotlin 中获取函数的参数列表
- c# - Xamarin Forms 项目中的 Imread 方法找不到我的图像
- ipython - Ipython 脚本中的 Shell 命令
- r - 不需要将`!!!`操作符导入包DESCRIPTION?
- javascript - 为什么当我执行 hasAttribute() 并且元素具有属性时,它返回 false?
- postgresql - 有什么方法可以在 sequalize PostgreSQL 中编辑自动增量值
- android - SwipeRefresherLayout 空指针
- java - 检查两个图像是否几乎相同(通过检查精灵)?
- android - 两个textview一个接一个不使用LinearLayout权重