1

I have a JSON response that I would like to parse using JSON.NET. I have done this with single values before but never when the response could contain an object that consist of an array as the errors property does below.

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

I would like to extract the error messages into a List. How do I specify that I want to grab the message property in the errors collection?

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

1 Answer 1

2

You could use

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

Then (Probably you'll send your json string as param )

        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();

        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.