[英]Deserialize json string with multiple objects
在调用 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);
}
这是我的 Model:
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: Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[myProjectNamespace.Models.MyModel]' because the type requires a JSON数组(例如 [1,2,3])正确反序列化。
动态object呢?
public async Task<dynamic> GetAsync(string url)
{
/*
Code to get the above JSON
*/
return Newtonsoft.Json.JsonConvert.DeserializeObject(res);
}
PS:安装Newtonsoft.Json
如果您有强类型 JSON 那么您需要创建一些模型 (DTO) 来表示 JSON 的结构。 注意: ABCD3
在Value2
和Value3
中有不同的类型,您应该根据您的数据自行定义
public class Root
{
public List<TargetObject> TargetObject { get; set; }
}
public class TargetObject
{
public string Value1 { get; set; }
public List<Value2> Value2 { get; set; }
public List<Value3> Value3 { get; set; }
}
public class Value2
{
public string ABC1 { get; set; }
public string ABC2 { get; set; }
public string ABC3 { get; set; }
}
public class Value3
{
public string ABCD1 { get; set; }
public string ABCD2 { get; set; }
public List<ABCD3> ABCD3 { get; set; }
}
public class ABCD3
{
public string ABCVal { get; set; }
public string Extra { get; set; }
}
然后
return JsonConvert.DeserializeObject<Root>(jsonString);
如果您只需要将TargetObject
的内容作为string
获取,请使用:
var jsonDoc = JsonDocument.Parse(jsonString);
var targetObject = jsonDoc.RootElement.GetProperty("TargetObject").GetRawText();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.