Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpResponseMessage.Content.ReadAsStringAsync don't deserialize JSON when it come from CreateErrorResponse

Tags:

json

c#

if i return from my selfhosted webapi

Request.CreateResponse(HttpStatusCode.OK, "YAY");

everything is fine.. so i can read it like that:

var responseStr = await Client.Content.ReadAsAsync<string>();
and then make something like "MessageBox.Show(responseStr);

if i return

Request.CreateErrorResponse(HttpStatusCode.NotFound, "something went wrong!");

and i read it out the same way or even with(doesn't matter how):

Client.Content.ReadAsStringAsync();

the string is not deserialized and i get an error when trying to parse / read as string.

if i read it as object .. it's fine.. but i can't perform object.ToString(); i get errors..

why? and how to fix it?

like image 679
darkdog Avatar asked Feb 20 '14 11:02

darkdog


1 Answers

I found that there were extra '\' and '"' in the returned JSON.
So before I serialize back to an object, I needed to remove the extra chars.

e.g.

string jsonString = httpResponseMessage.Content.ReadAsStringAsync()
                                               .Result
                                               .Replace("\\", "")
                                               .Trim(new char[1] { '"' });

List<VwAisItemMaster> vwAisItemMasterList = JsonConvert.DeserializeObject<List<VwAisItemMaster>>(jsonString);
like image 189
Carl Prothman Avatar answered Sep 17 '22 15:09

Carl Prothman