Custom replace for json encoding not outputting do

2019-05-10 02:52发布

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?

2条回答
Animai°情兽
2楼-- · 2019-05-10 03:33

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

查看更多
Luminary・发光体
3楼-- · 2019-05-10 03:43

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("\"", "\\\"");
查看更多
登录 后发表回答