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);
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.
i found the solution here it is
return new HttpResponseMessage()
{
Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json")
};
using Newtonsoft.Json.Linq;
string str = "Your String with Back Slashes";
str = JToken.Parse(str).ToString(); `// Now You will get the Normal String with "NO SLASHES"`
Most likely, the slashes are an artifact because you copied them out of the VisualStudio debugger. The debugger displays all strings in a way that they could be pasted into C/C# code. They aren't really in the transmitted data.
BTW: These slashes are backward slashes. A forward slash would look like this: /.
For the sake of seeing a "full" snippet of code, this is what I used to achieve a solution:
[AllowAnonymous]
[HttpGet]
public HttpResponseMessage GetAllMessages()
{
try
{
//Load Data Into List
var mm = new MessageManager();
List<Message> msgs = mm.GetAllMessages();
//Convert List Into JSON
var jsonmsgs = JsonConvert.SerializeObject(msgs);
//Create a HTTP response - Set to OK
var res = Request.CreateResponse(HttpStatusCode.OK);
//Set the content of the response to be JSON Format
res.Content = new StringContent(jsonmsgs, System.Text.Encoding.UTF8, "application/json");
//Return the Response
return res;
}
catch (Exception exc)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc);
}
}