I am just trying to build a json string for my unit test and unexpectedly the following code returns system format exception. The error message indicates that it is trying to parse date which is quite odd to me. I am not asking to parse date.
class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetJson());
Console.ReadKey();
}
static string GetJson(string dateStr = "", string lta = "5.25")
{
return String.Format("[{\"dateBooking\":\"{0}\",\"lta\":\"{1}\"}]", dateStr, lta);
}
}
It can be easily reproduced but I am adding exception details:
"An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: Input string was not in a correct format."
You need to escape the {
with {{
and the }
with }}
because String.Format
will search for an argument like {0:000}
but instead finds {"dateBooking ... }
which is no valid argument format. Thats why a FormatException raises.
return String.Format("[{{\"dateBooking\":\"{0}\",\"lta\":\"{1}\"}}]", dateStr, lta);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With