59

Given the code:

dynamic foo = new ExpandoObject();
foo.Bar = "something";
string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);

The output is below:

"{\"Bar\":\"something\"}"

When debugging a large json document it is hard to read - using the built in features of Newtonsoft.Json (not regex or hacks that could break things) is there any way to make the output a string with the valie:

{Bar: "something"}
morleyc
  • 2,169
  • 10
  • 48
  • 108
  • 6
    How are you viewing the output? It's being rendered as a string literal which doesn't fit with JSON.NET and `SerializeObject` alone unless it's being serialized a 2nd time. If you're viewing the value within VS (via Locals, Watch, etc.), then it's rendering the value as code, but should have an option to view as text instead. – Jonathan Lonowski Dec 01 '13 at 14:48
  • Yes that's from the debugger viewing a string variable in vs2012. I did look at the viewer options they are string, xml and i think html – morleyc Dec 01 '13 at 18:10
  • Refer this....you may get the solution.... http://stackoverflow.com/questions/13833900/return-json-but-it-includes-backward-slashes-which-i-dont-want – Mohan Gopi Feb 11 '15 at 05:39

10 Answers10

21

If this happens to you while returning the value from a WebApi method, try returning the object itself, instead of serializing the object and returning the json string. WebApi will serialize objects to json in the response by default; if you return a string, it will escape any double quotes it finds.

So instead of:

public string Get()
{
    ExpandoObject foo = new ExpandoObject();
    foo.Bar = "something";
    string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);
    return json;
}

Try:

public ExpandoObject Get()
{
    ExpandoObject foo = new ExpandoObject();
    foo.Bar = "something";
    return foo;
}
devRyan
  • 373
  • 4
  • 12
16

Try the JToken.Parse method. I've found that even though when I view JSON objects in the debugger and they are correct, when I go to manipulate them they end up being converted to literals (i.e. backslashes are added). The JToken.Parse method seems to avoid this.

var token = JToken.Parse(text);

So in the case of the original question it would be something like:

dynamic foo = new ExpandoObject();
foo.Bar = "something";
string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);
var token = JToken.Parse(json);
//Do stuff with token -- not json string

In my case specifically the issue was that using JObject.Add(json) would not recognize that my string was json and just insert the entire string as a single property. Once converted into a Jtoken however the JSON was interpreted correctly.

Rider Harrison
  • 441
  • 6
  • 12
10

What you see in debugger when looking at the json value is the string value that you should use in a C# file to obtain the same value.

Indeed you could replace

dynamic foo = new ExpandoObject();
foo.Bar = "something";
string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);

with

string json = "{\"Bar\":\"something\"}";

without changing the program's behaviour.

Thus, to obtain a different value, you should change how JsonConvert works, but JsonConvert conforms to the JSON standard, thus forget it!

If you are not actually serializing ExpandoObject (nor any other sealed class out of your control), you can use the DebuggerDisplayAttribute on the types that you are serializing in json, to define how the object will be shown during debug (in your code, the foo instance).

But a string is a string and VisualStudio is right: double-quotes must be escaped.

Giacomo Tesio
  • 7,144
  • 3
  • 31
  • 48
  • 4
    this happens when you SerializeObject an object from a web service. What you see in web browser output is that escaped string, which makes the output useless, unless you want to deal with that snafu on client side. No thank you, I'd much rather prefer to get proper json sent to my clients from my web service. In other words, my web service should return the string that I gave it, as I gave it. – Tuncay Göncüoğlu Jun 29 '16 at 08:58
  • 1
    @TuncayGöncüoğlu it sounds like you are returning a string object, which is getting serialized again into a JSON string. Post your issue as a question and we can help you solve it. – Cory Nelson Jul 14 '16 at 00:08
10

Old question but I found this,

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. Hope it helps.

S52
  • 419
  • 1
  • 6
  • 20
2

Instead of using Newstonsoft.Json you should employ the JavaScriptSerializer.Serialize Method:

dynamic foo = new ExpandoObject();
foo.Bar = "something";
var js = new JavaScriptSerializer( );
string json = js.Serialize(foo);

This method produces exactly the output you are looking for. I read about it here.

BdN3504
  • 1,693
  • 21
  • 29
2

Its Just simple make the return IHttpActionResult and return the object

  public IHttpActionResult Get()
    {

        ExpandoObject foo = new ExpandoObject();
        foo = //query result

        return ok(foo)
    }
Zulqarnain
  • 611
  • 7
  • 18
0

Hey I Just simply write out put to a file

 using (System.IO.StreamWriter file = 
            new System.IO.StreamWriter(@"jsonGonna.txt", true))
        {
            file.WriteLine(json);
        }

now just run the program and you will get without black slash and it good for big programs where you need to save JSON multiple times

Prageeth godage
  • 4,054
  • 3
  • 29
  • 45
0

Actually it has nothing to do with serializer. It's just because c# don't have single and double quotes concept like Javascipt does. So it can't show string with double quotes without escaping them. But if you want to put string into html/ cshtml without any escapes you just need to tell compliler that like so:

window.MYVAR = JSON.parse('@Html.Raw(ViewBag.MyStringFromCSharp)');
Saulius
  • 1,736
  • 20
  • 29
0

In case you're getting your data from a controller view method in such a format and finding it difficult to work with in JavaScript. Below is an easy work around:

const CleanUpDifficultJSonData = difficultJSonData => {
  const dummyElement = document.createElement('div');
  dummyElement.innerHtml = difficultJSonData;
  const cleanJSonData = JSON.parse(dummyElement.innerHtml);
  return cleanJSonData;
};

const difficultJSonData = "{\"Bar\":\"something\"}";

console.log('cleanJSonData: ', 
CleanUpDifficultJSonData(difficultJSonData));      
Bernard Oreva
  • 124
  • 1
  • 4
-1
    [HttpGet]
    public object Get(int id)
    {

        object result = "";
        var db = new dbEntities();
        var EO = new System.Dynamic.ExpandoObject() as IDictionary<string, Object>; //needed to return proper JSON without escape slashes
        try
        {

            IEnumerable<usp_GetComplaint_Result> aRow =  db.usp_GetComplaint(id);

            string DBL_QUOTE = new string(new char[] { '"' });
            result = "{";

            foreach (usp_GetComplaint_Result oneRow in aRow)
            {
                System.Reflection.PropertyInfo[] properties = typeof(usp_GetComplaint_Result).GetProperties();

                foreach(System.Reflection.PropertyInfo property in properties)
                {
                    var vValue = property.GetValue(oneRow) == null ? "null" : property.GetValue(oneRow);
                    EO.Add(property.Name,vValue);
                }
                break;
            }

        }
        catch (Exception ex)
        {
            result = ex.Message;
            EO.Add("Error", result);
        }
        finally
        {
            db.Dispose();
        }

        return Ok(EO);

    }
SEF
  • 9