使用JSON.Net解析数组的属性

时间:2018-05-16 17:34:10

标签: json.net

我有一个JSON响应,我想用JSON.NET解析。我之前使用单个值完成了此操作,但从来没有响应可以包含由数组组成的对象,如下面的errors属性所示。

{
  "code": "InvalidObject",
  "message": "payment object is invalid",
  "errors": [
    {
      "code": "AccountingApi",
      "message": "Paid amount cannot be greater than the amount of the invoice.",
      "resource": "payment",
      "field": "amount"
    },
        {
            "code": "AccountingApi",
      "message": "Payment has not been verified",
      "resource": "payment",
      "field": "verification"
        }
  ]
}

我想将错误消息提取到List中。如何指定我要抓取message集合中的errors属性?

List<string> errorMessages = parsedJson["errors"].ToList<string>();

1 个答案:

答案 0 :(得分:2)

您可以使用

    class Error
    {
        public string code { get; set; }
        public string message { get; set; }
        public string resource { get; set; }
        public string field { get; set; }
    }

    class Some
    {
        public string code { get; set; }
        public string message { get; set; }
        public List<Error> errors { get; set; }
    }

然后(可能你将你的json字符串作为参数发送)

        List<string>  parse()
        {
            var s = new StringBuilder();
            s.Append("{");
            s.Append("    \"code\": \"InvalidObject\",");
            s.Append("\"message\": \"payment object is invalid\",");
            s.Append("\"errors\": [");
            s.Append("{");
            s.Append("\"code\": \"AccountingApi\",");
            s.Append("\"message\": \"Paid amount cannot be greater than the amount of the invoice.\",");
            s.Append("\"resource\": \"payment\",");
            s.Append("\"field\": \"amount\"");
            s.Append("},");
            s.Append("{");
            s.Append("\"code\": \"AccountingApi\",");
            s.Append("\"message\": \"Payment has not been verified\",");
            s.Append("\"resource\": \"payment\",");
            s.Append("\"field\": \"verification\" ");
            s.Append("}");
            s.Append("]");
            s.Append("}");

            var json = s.ToString();
            var  obj  = JsonConvert.DeserializeObject<Some>(json);
            return obj.errors.Select(x => x.message).ToList();

        }