41

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);
peterh
  • 9,698
  • 15
  • 68
  • 87
riseres
  • 2,896
  • 3
  • 24
  • 38

18 Answers18

30

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.

id.ot
  • 2,641
  • 1
  • 28
  • 45
  • 2
    Certainly it helped me! I really appreciate it. I wonder how many devs fall in the same trap and try to find a hack around it. I have seen this unnecessary conversion allover the place. – usefulBee Mar 06 '15 at 19:42
  • I had this same issue. Thanks! – usr4896260 May 30 '17 at 13:05
  • This yes, but returning as Json does not pick up my JsonProperty in the attributes. Only the JsonConvert serializer seems to do that. For instance if I have a property of ActualTarget but want it to serialize as 'Actual-Target' in Json this doesn't seem to work. – Papa Burgundy Nov 29 '17 at 15:27
  • This was my problem, double serializing.. I'm an idiot – Imsopov Jan 11 '18 at 05:54
  • same issue...feels great to have it fixed. thank you for your post. – ScottG Sep 27 '18 at 15:50
  • That saved me from going around it with manual code removal and kept my code clean! Thank you! – Sotiris Zegiannis Jun 07 '19 at 13:08
27

i found the solution here it is

return new HttpResponseMessage() 
{
    Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json")
};
OneCricketeer
  • 126,858
  • 14
  • 92
  • 185
riseres
  • 2,896
  • 3
  • 24
  • 38
15
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"`
Gianmarco
  • 2,455
  • 22
  • 53
Maulik
  • 167
  • 1
  • 4
11

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: /.

Codo
  • 64,927
  • 16
  • 144
  • 182
4

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);
        }
    }
Andrew Birks
  • 583
  • 4
  • 24
4

After hours of trying to figure this out, one popular response to this question seemed to be spot on accurate for me. But, not in the manner I imagined.

My code was very very simple:

this.Request.CreateResponse(HttpStatusCode.Accepted, new JavaScriptSerializer().Serialize(obj));

I was sure the the popular response of "double serializing" did not apply to me. After all, I was explicitly serializing my object to JSON only once.

I tried this snippet:

new StringContent(json, System.Text.Encoding.UTF8, "application/json")

Which did not even seem to contain my data! Instead this is what i received:

{
  "Headers": [
    {
      "Key": "Content-Type",
      "Value": [
        "application/json; charset=utf-8"
      ]
    }
  ]
}

Hmmm... But lo and behold! Looking closely at my original response in the Swagger UI, and after copy and pasting it into a JSON beautifier - I was in fact somehow "double serializing". Using the following code is what yielded the correct JSON response:

 this.Request.CreateResponse(HttpStatusCode.Accepted, obj);

That's right! just send the serializable object directly, no need to serialize to JSON! Seems the response automagically serializes objects into JSON. Hope this helps!

EDIT: If you begin with a JSON string, like let's say from database, you can deserialize the string into an object and return that object - like so:

object obj = new JavaScriptSerializer().DeserializeObject(json);
this.Request.CreateResponse(HttpStatusCode.Accepted, obj);
Heriberto Lugo
  • 533
  • 7
  • 18
3

Mostly It occurs due to double serialization. I had same issue a while back where I had to serialize a collection into Json string and even after trying various workarounds I was unable to resolve it. So, at last removed all the serialization code and simply returned the collection object and the serialization was taken care of by default. So try removing the serialization code and simply returning the return type. Hope it helps someone with similar issues.

3

I have the same issue, the response contains \" when I use

        JObject res = processRequst(req);
        String szResponse = res.ToString(Formatting.None);
        return Request.CreateResponse<string>(HttpStatusCode.OK, szResponse);

And these backslashes \" are removed if I replaced the above code by

        JObject res = processRequst(req);
        return Request.CreateResponse<JObject>(HttpStatusCode.OK, res);
Nick
  • 3,359
  • 18
  • 29
  • 40
Shiyu
  • 87
  • 6
2

I have found that a combination of the answers work for me. I was double serializing as someone above mentioned. In order for the serialization to recognize your JsonProperty attribute you must use JsonConvert serializer. For instance, I have a property called ActualtTarget but need it to serialize as Actual-Target. The Json result will not recognize the JsonProperty when serializing, so I serialized with JsonConvert and just returned the string like below:

return Content(JsonConvert.SerializeObject(myData));
Papa Burgundy
  • 6,197
  • 6
  • 37
  • 48
1

I found the solution and its worked for me:

var json = JsonConvert.SerializeObject(sb.ToString(), Formatting.Indented);
response.Content = new StringContent(json, Encoding.UTF8 , "application/json");
1

This worked for me. Answered above by riseres user.

return new HttpResponseMessage() 
{
Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json")
};
1

In my case, the string from server including backsplash like:

{\"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}"

when the API GET the response value using POSTMAN, the backsplash still appear. It turn out, you need to format you string in the server before push back to client (POSTMAN). MS website indicate the way to do so: return Ok(JSON_string);

follow the guide from Microsoft, the problem is solve

public ActionResult Get (int id, int id1)
{
     JSON_string = "your backsplash string"
     return Ok(JSON_string); //it will automatically format in JSON (like eliminate backsplash)

}

https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-3.1

0

Here i found the solution:

                    response = response.replace("\"", "\\").replace("\\\\", "\"").replace("\\", "");
                JSONArray PackageData = new JSONArray(response);
                SelectSymbolList.clear();
                for (int i = 0; i < PackageData.length(); i++) {
                    JSONObject jsonData = PackageData.getJSONObject(i);
                    // get your array here
                }
Sufiyan Ansari
  • 1,362
  • 15
  • 21
0

In my case, I was looking at the JSON string in a debugger and I found that was adding the escaping. And when I printed JSON to console, it was without escape characters.

var jsonContent = JsonConvert.SerializeObject(obj); 
Console.WriteLine("HERE NO SLASHES"+ jsonContent); 

original: https://stackoverflow.com/a/46836331/4654957

Diego Venâncio
  • 4,095
  • 2
  • 31
  • 56
0

its worked for me using below code for .netcore project while convert datatable to json

var lst = dt.AsEnumerable()
.Select(r => r.Table.Columns.Cast<DataColumn>()
        .Select(c => new KeyValuePair<string, object>(c.ColumnName, r[c.Ordinal])
       ).ToDictionary(z => z.Key, z => z.Value)
).ToList();
safeena rasak
  • 340
  • 2
  • 4
  • 12
0

In my case in a Generic Handler this helped. if the given string is json will return in try otherwise will return in catch

private static dynamic TryParseJSON(string message)
    {
        try
        {
            var serializer = new JavaScriptSerializer();
            return serializer.Deserialize<dynamic>(message);
        }
        catch
        {
            return message;
        }
    }
yannisalexiou
  • 465
  • 10
  • 21
0

Answer suggested by Andrew Birks works for me

//Convert List Into JSON
var jsonString = JsonConvert.SerializeObject(dataTable);

//Create a HTTP response - Set to OK
var response = Request.CreateResponse(HttpStatusCode.OK);

//Set the content of the response to be JSON Format
response.Content = new StringContent(jsonString, System.Text.Encoding.UTF8, "application/json");

//Return the Response
return response;
-3

I found the solution and worked for me (Y)

var yourString = yourString.Replace("\\","");

I got it from here

Luis Lavieri
  • 3,689
  • 5
  • 32
  • 60
Sam khan
  • 190
  • 2
  • 16