【问题标题】:Parse JSON with dynamic property name使用动态属性名称解析 JSON
【发布时间】:2019-08-18 14:49:37
【问题描述】:

JSON 结构

{
  "error": "RecordInvalid",
  "description": "Record validation errors",
  "details": {
  "email": [
   {
     "description": "Email: mark.vaugh@gmail.com is already being used by another user",
     "error": "DuplicateValue"
   }
 ],
 "name": [
  {
    "description": "Name: is too short (minimum one character)",
    "error": "ValueTooShort"
  }
 ]
 }
 }

属性名称“details”、“details:email”和“details:name”是动态的(见截图)

这里是 POCO 类:

public class ZendeskError
{
    [JsonProperty("details")]
    public Dictionary<string, List<ErrorKeyValue>> ErrorDetails { get; set; }

    [JsonProperty("description")]
    public string ErrorDescription { get; set; }

    [JsonProperty("error")]
    public string Error { get; set; }
}
public class ErrorKeyValue
{
    public KeyValuePair<string, List<PropertyFailureInformation>> PropertyError { get; set; }

}

public class PropertyFailureInformation
{
    [JsonProperty("description")]
    public string Description { get; set; }

    [JsonProperty("error")]
    public string Error { get; set; }
}

除了绑定到类 PropertyFailureInformation 之外,一切都运行良好 - 请参见屏幕截图。

请告知我哪里出错了?

【问题讨论】:

  • 不应该只是public Dictionary&lt;string, List&lt;PropertyFailureInformation&gt;&gt; ErrorDetails { get; set; }吗?我不明白你为什么需要额外的KeyValuePair&lt;string, List&lt;PropertyFailureInformation&gt;&gt;,但也许我错过了一些东西。
  • @canton7 你说得对 - 谢谢!那行得通,让我很傻。

标签: c# asp.net-core json.net


【解决方案1】:

您不需要ErrorKeyValueErrorDetails 应该是:

public Dictionary<string, List<PropertyFailureInformation>> ErrorDetails { get; set; }

即:

public class ZendeskError
{
    [JsonProperty("details")]
    public Dictionary<string, List<PropertyFailureInformation>> ErrorDetails { get; set; }

    [JsonProperty("description")]
    public string ErrorDescription { get; set; }

    [JsonProperty("error")]
    public string Error { get; set; }
}

public class PropertyFailureInformation
{
    [JsonProperty("description")]
    public string Description { get; set; }

    [JsonProperty("error")]
    public string Error { get; set; }
}

See DotNetFiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 1970-01-01
    • 2016-10-21
    • 1970-01-01
    • 2023-03-14
    • 2015-06-24
    • 2021-12-13
    相关资源
    最近更新 更多