Custom replace for json encoding not outputting double quotes as expected

≯℡__Kan透↙ 提交于 2019-12-07 14:22:41

问题


After I created my own json encoder, I realized it was replacing double-quotes with two escaping backslashes instead of one.

I realize, now, that C# has a built in Json.Encode() method, and yes, I have gotten it to work, however, I am left baffled by why the following code (the json encoder I had built) didn't replace quotes as I would expect.

Here is my json encoder method:

public static string jsonEncode(string val)
{
    val = val.Replace("\r\n", " ")
             .Replace("\r", " ")
             .Replace("\n", " ")
             .Replace("\"", "\\\"")
             .Replace("\\", "\\\\");

    return val;
}

The replace call: Replace("\"", "\\\"") is replacing " with \\", which of course produces invalid json, as it sees the two backslashes (one as an escape character, much like the above C#) as a single 'real' backslash in the json file, thus not escaping the double-quote, as intended. The Replace("\\", "\\\\") call works perfectly, however (i.e., it replaces one backslash with two, as I would expect).

It is easy for me to tell that the Replace method is not performing the functions, based on my arguments, like I would expect. My question is why? I know I can't use Replace("\"", "\\"") as the backslash is also an escape character for C#, so it will produce a syntax error. Using Replace("\"", "\"") would also be silly, as it would replace a double-quote with a double-quote.

For better understanding of the replace method in C#, I would love to know why the Replace method is behaving differently than I'd expect. How does Json.Encode achieve this level of coding?


回答1:


You're replacing " with \" and then replacing any backslashes with two backslashes... which will include the backslash you've already created. Perform the operations one at a time on paper and you'll see the same effect.

All you need to do is reverse the ordering of the escaping, so that you escape backslashes first and then quotes:

return val.Replace("\r\n", " ")
          .Replace("\r", " ")
          .Replace("\n", " ")
          .Replace("\\", "\\\\")
          .Replace("\"", "\\\"");



回答2:


The problem is here:

Replace("\"", "\\\""); // convert " to \"
Replace("\\", "\\\\"); // which are then converted to \\"

The first line replaces " with \". The second line replaces those new \" with \\".

As Jon says, you need the replacement that escapes the escape character to run before introducing any escape characters.

But, I think you should use a real encoder. ;-)



来源:https://stackoverflow.com/questions/15275422/custom-replace-for-json-encoding-not-outputting-double-quotes-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!