JSON .NET-将当前JSON对象(例如{“ name”:“ value”})反序列化为类型'System.Collections.Generic.List`1

时间:2019-05-15 10:10:25

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

我阅读了很多有关此问题的主题,但找不到解决方案。我有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的序列化?

1 个答案:

答案 0 :(得分:2)

对于您的特定情况,由于字典实现了一个对象并接收了键值对,因此您可以使用字典而不是列表,您可以使用动态属性名称以及所需的任何值(字符串列表)

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;}
}