使用带有String.Format的转义字符串会导致格式异常

时间:2017-01-15 07:56:57

标签: c# string.format

尝试此操作时出现System.Format异常:

var jsonString = String.Format( @"{
    ""searchOptions"": {
        ""departurePosition"": { ""id"": {0} },
        ""arrivalPosition"": { ""id"": 376422 },
        ""travelModes"": [ ""Flight"", ""Train"", ""Bus"" ],
        ""departureDate"": ""2017-01-15"",
        ""passengers"": [
          {
            ""age"": 12,
            ""discountCards"": [ ]
          }
        ],
        ""userInfo"": {
          ""identifier"": ""0.jhvlf8amtgk"",
          ""domain"": "".com"",
          ""locale"": ""en"",
          ""currency"": ""EUR""
        },
        ""abTestParameters"": [ ]
    }
}", departurePosition);

在向服务器发送帖子请求时我需要这个。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

这可能是因为{}的使用 要转义{}使用{{}}

答案 1 :(得分:0)

OfirW已经分享了这个, string.Format() giving “Input string is not in correct format”

如果这只是一个变量,则常规字符串连接将正常工作。

var jsonString =  
@"{ ""searchOptions"": {
        ""departurePosition"": { ""id"": " + departurePosition + @"},
        ""arrivalPosition"": { ""id"": 376422 },
        ""travelModes"": [ ""Flight"", ""Train"", ""Bus"" ],
        ""departureDate"": ""2017-01-15"",
        ""passengers"": [
          {
            ""age"": 12,
            ""discountCards"": [ ]
          }
        ],
        ""userInfo"": {
          ""identifier"": ""0.jhvlf8amtgk"",
          ""domain"": "".com"",
          ""locale"": ""en"",
          ""currency"": ""EUR""
        },
        ""abTestParameters"": [ ]
  }
}";