JSON Deserialize with empty field c#

时间:2016-04-21 22:24:27

标签: c# json deserialization json-deserialization

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 个答案:

答案 0 :(得分: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).

答案 1 :(得分:2)

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.