3

I'm testing some api calls in c# and getting the following JSON response:

{
  "message": "The request is invalid. Model validation failed.",
  "validationErrors": {
    "": {
      "reasons": [
        "A customer must be added to the order before it can be placed."
      ]
    }
  }
}

I want to map this response to a class with a JSON Deserializer and I have no control over how the response is formed. How do I handle that empty field in validationErrors so that I can still access the reasons list in my object?

Note: when I ran it through json2csharp it gave this not too useful mapping for that field within the validationErrors class.

public __invalid_type__ __invalid_name__ {get;set;}

2 Answers 2

3

Deserialize to a Dictionary<string, ValidationError>:

public class ValidationError
{
    public List<string> reasons { get; set; }
}

public class RootObject
{
    public string message { get; set; }
    public Dictionary<string, ValidationError> validationErrors { get; set; }
}

This will work out-of-the-box with and . If you are using DataContractJsonSerializer (tagged as ) you will need to set DataContractJsonSerializer.UseSimpleDictionaryFormat = true (.Net 4.5 and above only).

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

1 Comment

Worked! Accessing a value with an empty key isn't my favorite thing in the world, but the api devs are at fault for that, not you.
3

If you have your own class which you're trying to deserealization, you can try to use Newtonsoft-Json to configure your Json property names by JsonPropertyAttribute and set it like:

public class YourModel
{
    [JsonProperty(name = "")
    public ValidationErrors { get; set; }
}

More examples here - link

Or, you can deserealize your property as a Dictionary<string, YourErrorObject> and use the first one item for access to errors.

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.