Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 759
Shyamal Parikh Avatar asked Nov 26 '25 22:11

Shyamal Parikh


1 Answers

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;
    }
}
like image 109
Gabriel Claudiu Georgiu Avatar answered Nov 29 '25 10:11

Gabriel Claudiu Georgiu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!