Jane Kins
Jane Kins

Reputation: 43

Using escaped string with String.Format results in Format Exception

I get a System.Format exception when trying this:

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 ?

Upvotes: 0

Views: 82

Answers (2)

Ankit
Ankit

Reputation: 2518

OfirW already shared this, string.Format() giving “Input string is not in correct 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"": [ ]
  }
}";

Upvotes: 0

Ofir Winegarten
Ofir Winegarten

Reputation: 9365

It's probably because the use of { and } To Escape the { and } use {{ and }}

Upvotes: 2

Related Questions