简体   繁体   English

Newtonsoft.Json 没有转义反斜杠的 SerializeObject

[英]Newtonsoft.Json SerializeObject without escape backslashes

Given the code:给定代码:

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

The output is below: output如下:

"{\"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:调试大型 json 文档时,很难阅读 - 使用 Newtonsoft.Json 的内置功能(不是正则表达式或可能破坏事物的 hack)是否有任何方法可以使 output 成为带有值的字符串:

{Bar: "something"}

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 方法返回值时发生这种情况,请尝试返回对象本身,而不是序列化对象并返回 json 字符串。 WebApi will serialize objects to json in the response by default;默认情况下,WebApi 会将响应中的对象序列化为 json; 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;
}

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.当您查看json值时,您在调试器中看到的是您应该在 C# 文件中使用以获得相同值的字符串值。

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!因此,要获得不同的值,您应该更改JsonConvert 的工作方式,但 JsonConvert 符合JSON 标准,因此忘记它!

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).如果您实际上没有序列化ExpandoObject (也没有任何其他不受您控制的密封类),您可以对您在 json 中序列化的类型使用DebuggerDisplayAttribute ,以定义在调试期间对象的显示方式(在您的代码中, foo实例)。

But a string is a string and VisualStudio is right: double-quotes must be escaped.但是字符串就是字符串,VisualStudio 是对的:必须对双引号进行转义。

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.就我而言,我正在调试器中查看 JSON 字符串,我发现它正在添加转义。

And when I printed JSON to console, it was without escape characters.当我将 JSON 打印到控制台时,它没有转义字符。 Hope it helps.希望能帮助到你。

Try the JToken.Parse method.试试 JToken.Parse 方法。 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 (ie backslashes are added).我发现即使我在调试器中查看 JSON 对象并且它们是正确的,当我去操作它们时,它们最终会被转换为文字(即添加了反斜杠)。 The JToken.Parse method seems to avoid this. JToken.Parse 方法似乎避免了这种情况。

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.就我而言,问题是使用 JObject.Add(json) 无法识别我的字符串是 json,而只是将整个字符串作为单个属性插入。 Once converted into a Jtoken however the JSON was interpreted correctly.一旦转换为 Jtoken,JSON 就会被正确解释。

Its Just simple make the return IHttpActionResult and return the object它只是简单地使返回 IHttpActionResult 并返回对象

  public IHttpActionResult Get()
    {

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

        return ok(foo)
    }

Instead of using Newstonsoft.Json you should employ the JavaScriptSerializer.Serialize Method :您应该使用JavaScriptSerializer.Serialize 方法,而不是使用 Newstonsoft.Json:

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 .在这里读到了它。

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现在只需运行该程序,您将不会获得黑色斜杠,这对于需要多次保存 JSON 的大型程序很有用

    [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);

    }

Actually it has nothing to do with serializer.实际上它与序列化器无关。 It's just because c# don't have single and double quotes concept like Javascipt does.这只是因为 c# 没有像Javascipt那样的单引号和双引号概念。 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:但是,如果您想将字符串放入html/ cshtml而不进行任何转义,您只需要像这样告诉编译器:

 window.MYVAR = JSON.parse('@Html.Raw(ViewBag.MyStringFromCSharp)');

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:如果您以这种格式从 controller 视图方法获取数据,并发现很难在 JavaScript 中使用。下面是一个简单的解决方法:

 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM