简体   繁体   English

将转义的字符串与String.Format一起使用会导致格式异常

[英]Using escaped string with String.Format results in Format Exception

I get a System.Format exception when trying this: 尝试这样做时,我得到一个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);

I need this when sending a post request to a server. 在向服务器发送发布请求时,我需要这个。

How can I solve this problem ? 我怎么解决这个问题 ?

可能是因为使用{}来逃避{}使用{{}}

OfirW already shared this, string.Format() giving “Input string is not in correct format” OfirW已经共享了此内容, string.Format()给出“输入字符串的格式不正确”

If this is just one variable, regular string concatenation will work fine. 如果这只是一个变量,则常规字符串串联将可以正常工作。

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"": [ ]
  }
}";

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

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