3

I have been trying to deserialize return response.Content string but in vain. WebApi action returns a modified modelState with additional custom errors.

On the MVC side, I tried the following methods none worked:

JsonDeserializer deserial = new JsonDeserializer();
  var json = deserial.Deserialize<dynamic>(response);

And

    var json = JsonConvert.DeserializeObject<WebApiReturnModel>(response.Content);

    public class WebApiReturnModel
    {
        public string Message { get; set; }

        public ModelStateDictionary ModelState { get; set; }
    }

Example of response.Content returned:

{
    "Message":"The request is invalid.",
    "ModelState":{
        "": ["Name Something is already taken.","Email '[email protected]' is already taken."]
            }
}

How to get this to work?

2
  • How is ModelStateDictionary designed? Commented Dec 29, 2015 at 12:00
  • @Amit That is default .Net implementation Commented Dec 29, 2015 at 12:05

1 Answer 1

1

I tried using the dynamic approach and for me this works:

var input = @"{
                ""Message"":""The request is invalid."",
                ""ModelState"":{
                            """": [""Name Something is already taken."",""Email '[email protected]' is already taken.""]
                }
            }";

// This uses JSON.Net, as your second snippet of code.
var json = JsonConvert.DeserializeObject<dynamic>(input);

// This will get: The request is invalid.
var message = json["Message"].Value;

foreach (var m in json["ModelState"][""])
{
    // This will get the messages in the ModelState.
    var errorMessage = m.Value;
}

If you don't know the names of the keys in ModelState, you can use a nested loop:

foreach (var m in json["ModelState"])
{
    foreach (var detail in m.Value)
    {
        // This will get the messages in the ModelState.
        var errorMessage = detail.Value;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

The only problem with json["ModelState"][""] is that the key has to be known before it can be used. There has to be a better way.

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.