Reputation: 109
I have a web api that returns the following json when user registration fails:
{
"$id":"1",
"Message":"The request is invalid.",
"ModelState": {
"$id":"2",
"": {
"$id":"3",
"$values": ["Name [email protected] is already taken."]
}
}
}
I have tried all sorts of things to deserialize it in c# in order to display the error message to the user without any luck.
Here's one on the things I have tried:
Any help on this will be greatly appreciated.
Thank you in advance
Upvotes: 4
Views: 2156
Reputation: 1553
Try this:
Define the following class:
class WebApiResponse
{
public string Message { get; set; }
public Dictionary<string, IList<string>> ModelState { get; set; }
}
Then use the Newtonsoft.Json
library to deserialize the json response as an instance of the WebApiResponse
class:
var jsonFromWebApiResponse = @"{""$id"":""1"",""Message"":""The request is invalid."",""ModelState"":{""$id"":""2"","""":{""$id"":""3"",""$values"":[""Name [email protected] is already taken.""]}}}";
var webApiResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<WebApiResponse>(jsonFromWebApiResponse);
foreach (var modelState in webApiResponse.ModelState)
{
foreach (var innerMessage in modelState.Value)
{
// Do something with the messages inside ModelState...
}
}
Upvotes: 2
Reputation: 950
I hope this solves your problem. I developed using vb.net and converted to c#. Not tested on c# but works on vb.net.
class SurroundingClass
{
private void Button1_Click(object sender, EventArgs e)
{
var FullResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(WebResult);
Newtonsoft.Json.Linq.JObject lv2 = FullResponse.Item("ModelState");
Newtonsoft.Json.Linq.JObject lv3 = lv2.Item("");
string DisplayResponse = FullResponse.Item("Message") + " " + lv3.Item("$values").First;
MessageBox.Show(DisplayResponse);
}
public string WebResult()
{
return "{'$id':'1','Message':'The request is invalid.','ModelState':{'$id':'2','':{'$id':'3','$values':['Name [email protected] is already taken.']}}}";
}
}
Upvotes: 0