我们有一个C#控制台应用程序,可以调用多个第三方API.我们从这些API中以杨森格式获取数据.我们正在try 将SON子序列化为已定义的类.问题在于json中的"custom_attribers"属性包含具有以下 struct 的对象:
{
...other properties
"custom_attributes": [
{
"attribute_code": "required_options",
"value": "simple"
},
{
"attribute_code": "category_ids",
"value": [
"2"
]
},
{
"attribute_code": "has_options",
"value": "0"
}
]
}
正如您所看到的,"值"属性可以具有"字符串"类型或"字符串[]"类型作为值.
目前,我们有以下代码:
public class MyApiResponseClass
{
... other properties
[JsonProperty("custom_attributes")]
public List<CustomAttribute> CustomAttributes { get; set; } = new();
}
public class CustomAttribute
{
[JsonProperty("attribute_code")]
public string AttributeCode { get; set; } = string.Empty;
[JsonProperty("value")]
public object Value { get; set; } = string.Empty;
}
var response = JsonConvert.DeserializeObject<MyApiResponseClass>(responseContent);
这会产生以下错误:
无法将当前SON数组(例如[1,2,3])反序列化为类型"System. Body",因为该类型需要一个SON基元值(例如字符串、数字、布尔值、空值)才能正确反序列化. 要修复此错误,可以将JSON更改为JSON基元值(例如字符串、数字、布尔值、空值),或者将反序列化类型更改为数组或实现集合接口(例如ICollect、IList)的类型,例如可以从JSON数组反序列化的List.JsonArrayProperty还可以添加到类型中,以强制其从杨森数组反序列化. 路径"items[0].custom_attribes [17]. value ',第1行,位置3119.'
如有任何帮助,我们将不胜感激!