【发布时间】:2021-02-24 15:19:30
【问题描述】:
调用 API 后我得到以下 JSON 响应:
{
"Item": "Some value",
"Status": "ST",
"Details": "something here...",
"TargetObject": [
{
"Value1": "1",
"Value2": [
{
"ABC1": "......",
"ABC2": "...",
"ABC3": "..."
}
],
"Value3": [
{
"ABCD1": "......",
"ABCD2": "...",
"ABCD3": [
{
"ABCVal": "123"
},
{
"Extra": "123"
}
]
}
]
}
]
}
我想要做的是从 TargetObject 返回值但是这个键里面有多个对象/数组所以我的问题是:我怎样才能只返回这些值并打印以下 JSON结果:
{
"TargetObject": [
{
"Value1": "1",
"Value2": [
{
"ABC1": "......",
"ABC2": "...",
"ABC3": "..."
}
],
"Value3": [
{
"ABCD1": "......",
"ABCD2": "...",
"ABCD3": [
{
"ABCVal": "123"
},
{
"Extra": "123"
}
]
}
]
}
]
}
这是我尝试过的:
public async Task<List<List<MyModel>>> GetAsync(string url)
{
/*
Code to get the above JSON
*/
//Trying to return the expected JSON
return JsonConvert.DeserializeObject<List<List<MyModel>>>(jsonString);
}
这是我的模型:
public class MyModel
{
public string TargetObject { get; set; }
public string Value1 { get; set; }
public string Value2 { get; set; }
public string ABC1 { get; set; }
public string ABC2 { get; set; }
public string ABC3 { get; set; }
public string Value3 { get; set; }
public string ABCD1 { get; set; }
public string ABCD2 { get; set; }
public string ABCD3 { get; set; }
public string ABCVal { get; set; }
public string Extra { get; set; }
}
目前我收到以下错误:
Newtonsoft.Json.JsonSerializationException:无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型“System.Collections.Generic.List`1[myProjectNamespace.Models.MyModel]”,因为类型需要一个 JSON 数组(例如 [1,2,3])才能正确反序列化。
【问题讨论】:
-
使用json to C# 或quicktype 之类的东西来构建你的类定义来支持你的json。您还会注意到为什么会出现该异常。
-
你的 json 有多“动态”,因为支持
Dictionary<string,string>来支持Value2之类的东西是一回事,但要支持任何键/值有点困难
标签: c# json asp.net-core