【发布时间】:2021-01-05 21:30:25
【问题描述】:
我正在尝试接收对象中包含数组的 JSON。
{"attr1":"value", "attr2":"value", "attr3": [{"chldattr1":"value", "chldattr2":"value"}], "attr4":"value"}
已创建类或将其反序列化为对象。
namespace Contracts
{
class Contract
{
public string Attr1 { get; set; }
public string Attr2 { get; set; }
public List<ChildElement> Attr3s { get; set; }
public string Attr4 { get; set; }
}
class ChildElement
{
public string ChldAttr1 { get; set; }
public string ChldAttr2 { get; set; }
}
}
当我尝试
List<Contract> items = JsonConvert.DeserializeObject<List<Contract>>(jsonString)
我得到的错误是
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Program.Contracts.Contract]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
我不知道如何解决这个问题。
【问题讨论】:
-
您的 json 不是合同列表,而是单个合同。
-
你
Attr3s属性名与json中的名称不匹配。