C#StringBuilder的以引号(forJSON)引号、StringBuilder、forJSON

2023-09-02 02:05:30 作者:陪你到世界尽头

我有建立一个JSON字符串(被发布到Web服务),我使用的C#StringBuilder类来做到这一点。问题是,当我插入引号,StringBuilder类逃脱他们。

I have build a JSON string (to be posted to a web service), and I used the C# StringBuilder class to do this. The problem is, that when I insert quotes, the StringBuilder class escapes them.

我目前正在建设的JSON字符串作为这样的:

I am currently building the JSON string as such:

StringBuilder dataJSON= new StringBuilder();
dataJSON.Append("{");
dataJSON.Append("  " + Convert.ToChar(34) + "data" + Convert.ToChar(34) + ": {");
dataJSON.Append("  " + Convert.ToChar(34) + "urls" + Convert.ToChar(34) + ": [");
dataJSON.Append("  {" + Convert.ToChar(34) + "url" + Convert.ToChar(34) + ": " + Convert.ToChar(34) + domain + "/" + path[0] + Convert.ToChar(34) + "}");
dataJSON.Append("  ,{" + Convert.ToChar(34) + "url" + Convert.ToChar(34) + ": " + Convert.ToChar(34) + domain + "/" + path[1] + Convert.ToChar(34) + "}");
dataJSON.Append("  ]");
dataJSON.Append("  }");
dataJSON.Append("}");

但是,下面的命令: dataJSON.ToString(); 结果字符串:

However, the command: dataJSON.ToString(); results in the string:

{  "data": {  "urls": [  {"url": "domain/test1.html"}  , {"url": "domain/test2.html"}  ]  }}

注意转义引号?这是真的搞砸了我,因为服务器不能处理的斜杠。

Notice the escaped quotes? This is really screwing me up, because the server can't handle the slashes.

我希望(这帖细到我时,我用PHP服务器)的应该的是:

My desired (which posts fine to my server when I use PHP) should be:

{  "data": {  "urls": [  {"url": "domain/test1.html"}  , {"url": "domain/test2.html"}  ]  }}

有没有办法得到一个字符串在C#中包括引号,这将导致所需的字符串?

Is there ANY way to get a string in C# to include quotes that will result in the desired string?

非常感谢! 布雷特

推荐答案

快速监视/监视窗口将增加额外的 。如果你在文本查看展示台,你不会看到他们:

The QuickWatch/Watch window will add the extra in. If you view it in the Text Visualizer, you will not see them:

快速监视:

"{  "data": {  "urls": [  {"url": "domain/path1"}  ,{"url": 
    "domain/path2"}  ]  }}"

展示台(实际输出):

Visualizer (the actual output):

{  "data": {  "urls": [  {"url": "domain/path1"}  ,{"url": "domain/path2"}  ]  }}

表示该报价已经越狱,将包含在最终的字符串作为你期望的那样。即有无可厚非和您的输出。

The indicates that the quotes have been escaped and will be included in the final string as you're expecting them to be. I.e. there's nothing wrong with your output.

NB。我用而不是 Convert.ToChar(34)当我测试这一点。的

NB. I used """ instead of Convert.ToChar(34) when I tested this.