解析具有动态属性名称的JSON

时间:2019-08-18 14:49:37

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

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"
  }
 ]
 }
 }

属性名称“详细信息”,“详细信息:电子邮件”和“详细信息:名称”是动态的(请参见屏幕截图) enter image description here

以下是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之外,其他所有方法都运行良好-参见屏幕截图。 enter image description here

请告诉我我要去哪里错了?

1 个答案:

答案 0 :(得分:2)

您不需要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