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?
The problem is here:
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. ;-)
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: