1

I'm trying to do the following:

 var policyBuilder = new StringBuilder();    

 var expiration = DateTime.UtcNow.AddDays(1).ToString("s") + "Z";

 policyBuilder.AppendFormat("{ \"expiration\": \"{0}\",\n", expiration);

However, the last line throws the following exception:

 An exception of type 'System.FormatException' occurred in mscorlib.dll 
 but was not handled in user code

 Additional information: Input string was not in a correct format.

'expiration' is a string, so why am I getting this error?

Thanks

djst
  • 31
  • 4
  • 2
    Do you want a `{` character at the start of the output? – Rawling Feb 25 '16 at 12:15
  • I would guess that you probably _do_ want the `{` character in the output, as it appears you're trying to build up a JSON string using a `StringBuilder`. There are better ways to do this. – James Thorpe Feb 25 '16 at 12:16
  • Yes. I figured out that it works fine if I add another { at the start of the string like this: policyBuilder.AppendFormat("{{ \"expiration Why is this? – djst Feb 25 '16 at 12:19
  • @djst: that's explained in the link i've provided in my answer ;) – Tim Schmelter Feb 25 '16 at 12:22
  • Yep, I'm trying to build a string using the json format. I wont be serializing it. Its for doing AWS a3 policy signing. [link]http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-HTTPPOSTConstructPolicy.html#sigv4-HTTPPOSTExpiration – djst Feb 25 '16 at 12:23
  • @TimSchmelter Thanks for the link! – djst Feb 25 '16 at 12:24
  • _"I wont be serializing it"_ Well, you don't serialise the JSON string itself - the idea is you'd build an object that has the properties you want, and serialise _that_. Even without doing that though, there are things around that let you build up a JSON string without serialising objects that will handle this sort of stuff for you (braces and quoting key names/values etc) – James Thorpe Feb 25 '16 at 12:25
  • Duplicate? http://stackoverflow.com/q/91362/447156 – Soner Gönül Feb 25 '16 at 12:26
  • @JamesThorpe thanks for the help and for setting that straight. – djst Feb 25 '16 at 12:28

1 Answers1

1

If you want a { at the beginning you have to use two:

policyBuilder.AppendFormat("{{ \"expiration\": \"{0}\",\n", 10);

See: Escaping Braces in Composite Formatting

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. ....

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939