Odd System.Format Exception [duplicate]

╄→гoц情女王★ 提交于 2019-12-19 09:41:33

问题


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


回答1:


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);


来源:https://stackoverflow.com/questions/30421589/odd-system-format-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!