1

I'm developing SDK for Web API. I make http call using httpClient to endpoint and if there are some errors I got the following response with status code 400

{
    "errors": {
        "InstanceId": [
            {
                "code": "GreaterThanValidator",
                "message": "'InstanceId' must be greater than '0'."
            }
        ],
        "Surcharges[0]": [
            {
                "code": null,
                "message": "Surcharge Name is invalid. It should not be empty."
            }
        ]
    }
}

In my application (SDK) I have class that should contain a collection of grouped errors.

 public class ErrorResponse
    {
        private readonly IDictionary<string, IList<Error>> _errors;

        public ErrorResponse()
        {
            _errors = new Dictionary<string, IList<Error>>();
        }

        public ErrorResponse(string propertyName, string code, string message)
            : this()
        {
            AddError(propertyName, code, message);
        }

        public IReadOnlyDictionary<string, IList<Error>> Errors =>
            new ReadOnlyDictionary<string, IList<Error>>(_errors);

        public void AddError(string propertyName, string code, string message)
        {
            if (_errors.ContainsKey(propertyName))
            {
                _errors[propertyName].Add(new Error(code, message));
            }
            else
            {
                _errors.Add(propertyName, new List<Error> { new Error(code, message) });
            }
        }
    }

How can I deserialize that json to ErrorResponse class? I've tried this but errors always empty:

string content = await responseMessage.Content.ReadAsStringAsync();
var validationErrors = JsonConvert.DeserializeObject<ErrorResponse>(content);

How can I do that in proper way?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Pr.Dumbledor
  • 636
  • 1
  • 11
  • 29

1 Answers1

1

Adding a JsonPropertyAttribute will instruct json.net to deserialize to the private field.

I.E.

public class ErrorResponse
{
    [JsonProperty("errors")]
    private readonly IDictionary<string, IList<Error>> _errors;

    public ErrorResponse()
    {
        _errors = new Dictionary<string, IList<Error>>();
    }

    //...
}
Eric Damtoft
  • 1,353
  • 7
  • 13