Shyamal Parikh
Shyamal Parikh

Reputation: 3068

RestSharp: Deserialize json string

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?

Upvotes: 3

Views: 1034

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

Upvotes: 1

Related Questions