52

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
  • 11,875
  • 18
  • 85
  • 108
riseres
  • 3,004
  • 4
  • 28
  • 40

19 Answers19

37

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
  • 3,071
  • 1
  • 32
  • 47
  • 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
29

i found the solution here it is

return new HttpResponseMessage() 
{
    Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json")
};
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
riseres
  • 3,004
  • 4
  • 28
  • 40
18
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,536
  • 25
  • 57
Maulik
  • 197
  • 1
  • 4
13

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
  • 75,595
  • 17
  • 168
  • 206
  • An easy way to overcome this is to add the variable to Visual Studio Watch (Right click on the variable while debugger is running and choose "Add Watch"). In the watch panel, add a comma and nq (no quotes) after the name like "json, nq" -- then you can copy the value preserving original delimiters, tabs, and line breaks. – llessurt May 24 '23 at 20:31
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
  • 792
  • 9
  • 26
4

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.

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
  • 589
  • 7
  • 19
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
  • 4,820
  • 18
  • 31
  • 47
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,397
  • 6
  • 42
  • 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://learn.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,780
  • 20
  • 22
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
  • 5,698
  • 2
  • 49
  • 68
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
  • 390
  • 2
  • 5
  • 16
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
  • 605
  • 12
  • 25
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;
0
string jsonString = JsonConvert.SerializeObject(jsonMQTTPayLoad);

"{"Name": "John", "LastName": "Doe", "Age": 199 }";

 var stringwithoutbackslash = JObject.Parse(jsonString);

{ "Name": "John", "LastName": "Doe", "Age": 199 }

reza ul
  • 9
  • 3
-3

I found the solution and worked for me (Y)

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

I got it from here

Luis Lavieri
  • 4,064
  • 6
  • 39
  • 69
Sam khan
  • 220
  • 4
  • 17