0

I am having issue with String.Format on a verbatim string with escaped curly braced.

It's raising a FormatError() Exception:Message: System.FormatException : Input string was not in a correct format.

    String s = $@"{{ ""ver"": ""1.0"",""userId"": ""{0}""}}";
    String.Format(s, "1234")
Rajan Sharma
  • 2,211
  • 3
  • 21
  • 33
SwissFr
  • 178
  • 1
  • 12
  • 3
    Why are you using string.Format over string interpolation? – Twenty Jul 31 '19 at 06:45
  • 3
    Don't use `string.Format` **or** string interpolation to generate JSON. Create an anonymous object and use JSON.NET instead. – mjwills Jul 31 '19 at 06:46
  • I only need to generate a json string encoded in a specifc format for specifc test case. I don't think using JSON.NET library add value here. – SwissFr Jul 31 '19 at 06:52
  • 2
    I disagree @SwissFr. a) If you did it that way you'd avoid having to ask this question. b) If the `userId` has contents that require escaping / encoding for JSON then your current code won't work. – mjwills Jul 31 '19 at 07:02

1 Answers1

3

You are using the C# string interpolation special character "$", however, you are using positional parameters in your template.

It should be:-

String s = @"{{ ""ver"": ""1.0"",""userId"": ""{0}""}}";

String.Format(s, "1234").Dump();

Or just:-

var userId = 1234;

String s = $@"{{ ""ver"": ""1.0"",""userId"": ""{userId}""}}";

If your intention is to generate JSON output, a more appropriate method would be to create your object and serialize it using the Newtonsoft.Json package:-

var x = new
{
    ver = "1.0",
    userId = "1234"
};

var s = JsonConvert.SerializeObject(x);
Aleks
  • 1,629
  • 14
  • 19