2

I receive the following JSON from a Web API that lists the errors that were found in a POST. There can be more than one key-value pair in ModelState, depending how many errors were found. The only problem is that there are square brackets around the values. So when I deserialize with JSON.net there is an Unexpected token error.

My solution now is to do a search and replace for those brackets and then deserialize, which does work. But is there a better solution?

My class

public class Error
{
    public string Message { get; set; }
    public Dictionary<string, string> ModelState { get; set; }
}

The JSON

{
    "Message": "The request is invalid.",
    "ModelState": {
        "member.Gender": ["An error has occurred."],
        "member.MemberID": ["The MemberID field is required."],
        "member.BoardMemberID": ["The BoardMemberID field is required."],
    }
}

How I deserialize now

Error error = JsonConvert.DeserializeObject<Error>(jsonString.Replace("[", "").Replace("]", ""));
VDWWD
  • 33,993
  • 20
  • 58
  • 76
  • [More info](http://stackoverflow.com/questions/36688321/what-is-the-purose-of-using-square-brackets-in-json) – stuartd Feb 21 '17 at 14:35

3 Answers3

3

you will want ModelState to be a Dictionary<string, List<string>> instead of Dictionary<string, string>

i.e.

public class Error
{
    public string Message { get; set; }
    public Dictionary<string, List<string>> ModelState { get; set; }
}
tocsoft
  • 1,444
  • 16
  • 18
  • Accepted your answer as the correct one since all thee are almost identical, but yours was the first. – VDWWD Feb 21 '17 at 17:08
3

just change your model to the following

public class Error
    {
        public string Message { get; set; }
        public Dictionary<string, string[]> ModelState { get; set; }
    }

and the deserialization will look like the following

Error error = JsonConvert.DeserializeObject<Error>(jsonString);  
BRAHIM Kamel
  • 13,117
  • 31
  • 46
2

To accomplish your task, modify the Error class in the following manner:

public class Error
{
    public string Message { get; set; }
    public Dictionary<string, List<string>> ModelState { get; set; }
}
Pasick
  • 384
  • 2
  • 7