Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Json, but it includes backward slashes "\", which I don't want

I use MVC4 web-api, c#, and want to return Json using Json.net.

The problem is it comes with "backward slashes".

I also added this code to Global.asax. GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

Here is what it returns:

"{\"cid\":1,\"model\":\"WT50JB\",\"detail\":\"sdf??\",\"unit\":2,\"time_in\":\"2012-12-11T19:00:00\",\"time_out\":\"2012-12-12T13:00:06.2774691+07:00\",\"time_used_dd\":0.0,\"time_used_hh\":0.0}" 

So what I want to see is this: {"cid":1,"model":"WT50JB","detail":"sdf??","unit":2,"time_in":"2012-12-11T19:00:00","time_out":"2012-12-12T13:08:50.5444555+07:00","time_used_dd":0.0,"time_used_hh":0.0}

Here is JsonConvertor

string json = JsonConvert.SerializeObject(myObj); 
like image 598
riseres Avatar asked Dec 12 '12 06:12

riseres


People also ask

Why does my JSON have backslash?

Those backslashes are escape characters. They are escaping the special characters inside of the string associated with JSON response. You have to use JSON. parse to parse that JSON string into a JSON object.

How do I get rid of extra slashes in JSON?

Replace slash everywhere in the string----------->str =str. replace(/\//g,""); You can convert back to JSON object again using-->var output =JSON. parse(str);


2 Answers

I had the same issue, until just a few moments ago. Turns out that I was "double serializing" the JSON string. I use a jQuery $.getJson( AJAX call to a JsonResult controller action. And because the action builds a C# Generic List<t> I thought that I had to use JSON.net/NewtonSoft to convert the C# Generic List<t> to a JSON object before returning the JSON using the following:

return Json(fake, JsonRequestBehavior.AllowGet); 

I didn't have to use the JsonConvert.SerializeObject( method after all, evidently this return will conver the serialization for us.

Hope it helps you or someone else too.

like image 114
id.ot Avatar answered Sep 26 '22 20:09

id.ot


i found the solution here it is

return new HttpResponseMessage()  {     Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json") }; 
like image 32
riseres Avatar answered Sep 26 '22 20:09

riseres