【问题标题】:How do I deserialize a Json Object with an Array inside it如何反序列化带有数组的 Json 对象
【发布时间】: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&lt;Contract&gt; items = JsonConvert.DeserializeObject&lt;List&lt;Contract&gt;&gt;(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中的名称不匹配。

标签: c# arrays json


【解决方案1】:
namespace Contracts
{
    public class Contract
    {
        [JsonProperty("attr1")]
        public string Attr1 { get; set; }
        [JsonProperty("attr2")]
        public string Attr2 { get; set; }
        [JsonProperty("attr3")]
        public List<ChildElement> Attr3s { get; set; }
        [JsonProperty("attr4")]
        public string Attr4 { get; set; }        
    }
    public class ChildElement
    {
        [JsonProperty("chldattr1")]
        public string ChldAttr1 { get; set; }
        [JsonProperty("chldattr2")]
        public string ChldAttr2 { get; set; }
    }
}

Contract contract = JsonConvert.DeserializeObject<Contract>(jsonString);

您需要确保类的属性名称与 json 属性的名称匹配。使用[JsonProperty("name")] 属性来解决这个问题。

您的 Json 是单个对象。您不能将其反序列化为列表。

【讨论】:

  • 谢谢,我在复制和粘贴该行时忽略了反序列化到列表。
  • @RadialWaves 如果这回答了你的问题,我建议点击投票下的 ✔ 来标记这个回答
【解决方案2】:

反序列化器无法识别 attr3 与 Attr3s 相同。 要么将 Attr3s 更改为 Attr3,要么使用 [JsonProperty("name")] 指定 jsonproperty 名称

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    • 2016-10-02
    相关资源
    最近更新 更多