反序列化 JSON 对象

Deserialise JSON Object

我有一个 json 对象,如下所示:

[
    {"attributes": []},
    {"attribute_values": []},
    {"digital_assets": []},
    {"products": []},
]

所以我想如果我创建以下 c# class,我可以使用 newtonsofts JsonConvert.Deserialize<ProductContainer>():

直接反序列化它
public class ProductContainer
{
    [JsonProperty(PropertyName = "attributes")]
    public AttributeEntity[] Attributes { get; set; }

    [JsonProperty(PropertyName = "attribute_values")]
    public AttributeValueEntity[] AttributeValues { get; set; }

    [JsonProperty(PropertyName = "digital_assets")]
    public DigitalAssetEntity[] DigitalAssets { get; set; }

    [JsonProperty(PropertyName = "products")]
    public ProductEntity[] Products { get; set; }
}

但是,我收到以下错误:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ProductContainer' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path '', line 1, position 1.

我想可能是因为我的JSON格式不对。我要更改什么才能使其正常工作(在 JSON 文件或 C# class 中)

正如您在 Json 字符串中看到的那样,它是一个 array 对象。
我在 答案中描述了它们之间的区别。

问题是您的 Dictionary 类型包含 string 作为键和 array 作为值。

你的情况:

[
    {"attributes": []},
    {"attribute_values": []},
    {"digital_assets": []},
    {"products": []},
]

你必须先反序列化这个让我们说 JObject[]List<JObject> :

var objects = JsonConvert.Deserialize<List<JObject>>();

然后处理每个对象并找出键值并分配值,或者您可以只更改 Json 对象的第一个和最后一个字符:

string newJsonString = "{" + oldJsonString.Substring(1, oldJsonString.Length - 2) + "}";

哪个 return :

{
    {"attributes": []},
    {"attribute_values": []},
    {"digital_assets": []},
    {"products": []},
}

小提示
这仍然是 return 一个包含键值对的对象,其中键的类型为 string,值是和 array 的某物。但是使用第二种方法,您可以使用 JsonConvert.Deserialize<Dictionary<string, JObject>>(); 反序列化它,然后反序列化每个对象以更正类型,例如:

var dictionaryResult = JsonConvert.Deserialize<Dictionary<string, JObject>>();
meResultObject.Attributes = JsonConvert.Deserialize<List<AttributeEntity>>(dictionaryResult["attributes"].ToString());

如果您想将 JSON 字符串反序列化为您的 C# 对象,您需要将其设为 JSON 对象(而非数组):

{
    "attributes": [],
    "attribute_values": [],
    "digital_assets": [],
    "products": [],
}

如果您需要保留原始 JSON 数组而不是限制使用不同的结构进行反序列化,例如:

JsonConvert.DeserializeObject<List<Dictionary<string, object>>(obj);