简体   繁体   English

在c#中转义字符串中的双引号

[英]Escaping a double quotes in string in c#

I know this has been covered lots of times but I still have a problem with all of the solutions. 我知道这已被覆盖很多次但我仍然遇到所有解决方案的问题。

I need to build a string to send to a JSON parser which needs quotes in it. 我需要构建一个字符串以发送到需要引号的JSON解析器。 I've tried these forms: 我试过这些形式:

string t1 = "[{\"TS\"}]";
string t2 = "[{" + "\"" + "TS" + "\"" + "}]";
string t3 = @"[{""TS""}]"; 
Debug.Print(t1);
Debug.Print(t1);
Debug.Print(t1);

The debug statement shows it correctly [{"TS"}] but when I look at it in the debugger and most importantly when I send the string to my server side json parser is has the escape character in it: "[{\\"TS\\"}]" debug语句正确地显示它[{“TS”}]但是当我在调试器中查看它时,最重要的是当我将字符串发送到我的服务器端时,json解析器中包含转义字符:“[{\\”TS \\ “}]”

How can I get rid of the escape characters in the actual string? 如何摆脱实际字符串中的转义字符?

The debug statement shows it correctly [{"TS"}] but when I look at it in the debugger and most importantly when I send the string to my server side json parser is has the escape character in it: "[{\\"TS\\"}]" debug语句正确地显示它[{“TS”}]但是当我在调试器中查看它时,最重要的是当我将字符串发送到我的服务器端时,json解析器中包含转义字符:“[{\\”TS \\ “}]”

From the debugger point of view it will always show the escaped version (this is so you, as the developer, know exactly what the string value is). 从调试器的角度来看,它将始终显示转义版本(这是因为开发人员确切地知道字符串值是什么)。 This is not an error. 这不是错误。 When you send it to another .Net system, it will again show the escaped version from the debugger point of view. 当您将其发送到另一个.Net系统时,它将再次从调试器的角度显示转义版本。 If you output the value, (Response.Write() or Console.WriteLine()) you will see that the version you expect will be there. 如果输出值(Response.Write()或Console.WriteLine()),您将看到您期望的版本。

If you highlight the variable (from the debugger) and select the dropdown next to the magnifying glass icon and select "Text Visualizer" you will see how it displays in plain text. 如果突出显示变量(来自调试器)并选择放大镜图标旁边的下拉菜单并选择“Text Visualizer”,您将看到它以纯文本显示的方式。 This may be what you are looking for. 这可能就是你要找的东西。

Per your comments, i wanted to suggest that you also watch how you convert your string in to bytes. 根据您的意见,我想建议您也观察如何将字符串转换为字节。 You want to make sure you encode your bytes in a format that can be understood by other machines. 您希望确保以其他计算机可以理解的格式对字节进行编码。 Make sure you convert your string into bytes using a command as follows: 确保使用命令将字符串转换为字节,如下所示:

System.Text.Encoding.ASCII.GetBytes(mystring);

I have the sneaking suspicion that you are sending the bit representation of the string itself instead of an encoded version. 我怀疑你是在发送字符串本身的位表示而不是编码版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM