Custom replace for json encoding not outputting double quotes as expected

我们两清 提交于 2019-12-05 18:38:02

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("\"", "\\\"");

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

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