Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

.net - C# StringBuilder with Quotes (forJSON)

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.

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

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.

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

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

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

Many thanks! Brett

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

QuickWatch:

"{  "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. I used """ instead of Convert.ToChar(34) when I tested this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...