自定义替换json编码不按预期输出双引号 [英] Custom replace for json encoding not outputting double quotes as expected
问题描述
创建了自己的json编码器后,我意识到它用两个转义的反斜杠代替了双引号,而不是一个。
After I created my own json encoder, I realized it was replacing double-quotes with two escaping backslashes instead of one.
我意识到,现在,C#具有一个内置的 Json.Encode()
方法,是的,我已经开始使用它了,但是,为什么下面的代码(我使用的json编码器)让我感到困惑
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.
这是我的json编码器方法:
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;
}
替换调用: Replace( \ , \\\)
将
替换为 \\
,它当然会生成无效的json,因为它在json文件中将两个反斜杠(一个作为转义字符,类似于上面的C#)视为单个真实反斜杠,因此不会转义双引号, 如预期。 Replace( \\, \)
调用可以完美地工作,但是(即,它将一个反斜杠替换为两个反斜杠,因为
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).
根据我的论据,我很容易说出Replace方法没有执行功能,就像我期望的那样。我的问题是为什么?我知道我不能使用 Replace( \, \\)
,因为反斜杠也是C#的转义字符,因此它将产生语法错误。使用 Replace( \, \)
也是很愚蠢的,因为它将用双引号替换双引号。
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.
为了更好地理解C#中的replace方法,我想知道为什么Replace方法的行为与我预期的不同。 Json.Encode
如何实现此级别的编码?
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?
推荐答案
您将
替换为 \
,然后 then 用两个反斜杠替换任何反斜杠。 ..其中将包含您已经创建的反斜杠。一次在纸上执行一次操作,您将看到相同的效果。
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("\"", "\\\"");
这篇关于自定义替换json编码不按预期输出双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!