简体   繁体   中英

String.Format in Double Quotes in C#

Is anybody can help me with string.Format for below line. In '2056' I need to pass as {0}.

string body = @"{""idTimeSerie"":""2056"",""idTso"":-1}";

Due to double quotes I can't get it to execute.

I've tried in this way but no success.

string body = string.Format
                    (@"{""idTimeSerie"": "" \"{0}\" "",""idTso"":-1}", countryID);

you have to escape the curly braces

replace { to {{

string body = @"{{""idTimeSerie"":""2056"",""idTso"":-1}}";

Edit : From MSDN - Another way of Escaping

Opening and closing braces are interpreted as starting and ending a format item. Consequently, you must use an escape sequence to display a literal opening brace or closing brace. Specify two opening braces ("{{") in the fixed text to display one opening brace ("{"), or two closing braces ("}}") to display one closing brace ("}"). Braces in a format item are interpreted sequentially in the order they are encountered. Interpreting nested braces is not supported.

int value = 6324;
string output = string.Format("{0}{1:D}{2}", 
                             "{", value, "}");
Console.WriteLine(output);
// The example displays the following output: 
//       {6324}

Try this:

string body = string.Format(@"{{ ""idTimeSerie"": ""{0}"", ""idTso"": -1 ", countryID) + "}";

Explanation:

1) When using the @ flavor of string literals, double quotes are indicated by "" (two consecutive double quotes).

See MSDN:

@"""Ahoy!"" cried the captain." // "Ahoy!" cried the captain.

2) Use {{ and }} to indicate a literal { and } respectively in your string format.

See MSDN (Escaping Braces):

Specify two opening braces ("{{") in the fixed text to display one opening brace ("{"), or two closing braces ("}}") to display one closing brace ("}").

你可以这样做:

string body = string.Format("{{\"idTimeSerie\":\"{0}\",\"idTso\":-1}}", countryID);

Don't use a verbatim string in this case. I suspect you want:

string body = string.Format("{\"idTimeSerie\":\"{0}\",\"idTso\":-1}", countryID);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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