Search code examples
c#jsondeserializationjson-deserialization

JSON Deserialize with empty field c#


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

Solution

  • 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).