【问题标题】:JSON .NET - annot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1JSON .NET - 无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.List`1
【发布时间】:2019-05-15 10:10:25
【问题描述】:

我阅读了很多关于这个问题的主题,但找不到解决方案。我有 AP 返回的 JSON

{
    "Version": "XXX",
    "StatusCode": 400,
    "RequestId": "XXX",
    "Success": false,
    "ValidationMessages": {
        "SomeTable[0].PropName": [
       "This field is invalid"
        ],
        "SomeTable[1].PropName": [
            "This field is invalid"
        ],
        "SomeTable[0].OtherProp": [
            "This field is invalid"
        ]
    },
    "Result": {}
}

我创建了类:

public class MyResponse
{
    public string Version { get; set; }
    public string StatusCode { get; set; }
    public string RequestId { get; set; }
    public bool Success { get; set; }
    public SomeResult Result { get; set; }

    public List<KeyValuePair<string, List<string>>> ValidationMessages { get; set; }
}

当我尝试反序列化 JSON 时,我从标题中收到错误消息。如何实现动态ValidationMessages的序列化?

【问题讨论】:

  • json 中的 ValidationMessages 不是一个集合,它是一个对象,您正试图将其反序列化为一个集合。这就是您收到此错误的原因

标签: c# json json.net json-deserialization


【解决方案1】:

对于您的特定场景,您可以使用字典而不是列表,因为字典实现了一个对象并接收一个键值对,您可以拥有一个动态属性名称和您需要的任何值(字符串列表)

public class MyResponse
{
  public string Version { get; set; }
  public string StatusCode { get; set; }
  public string RequestId { get; set; }
  public bool Success { get; set; }
  public SomeResult Result { get; set; }
  public Dictionary<string, List<string>>  ValidationMessages {get;set;}
}

【讨论】:

  • 甚至是SortedList&lt;string, string[]&gt;
  • 我的评论没有保存。非常感谢。效果很好。
猜你喜欢
  • 2014-02-16
  • 2015-02-23
  • 1970-01-01
  • 2016-02-05
  • 1970-01-01
  • 2021-08-10
  • 1970-01-01
相关资源
最近更新 更多