C# 字符串格式化包含{}字符导致的问题
需求
在字符串格式化的时候包含{}字符时, 会发生报错格式化异常
代码:
string.Format("{\"type1\":{0},\"type2\":{1},\"type3\":{2}}", "1", "2", "3");
报错内容:
System.FormatException: Input string was not in a correct format.
解决
对于{content, {0}}这种嵌套格式, 需要{{content , {0}}}
string.Format("{{\"type1\":{0},\"type2\":{1},\"type3\":{2}}}", "1", "2", "3");
官方文档:
https://docs.microsoft.com/en-us/dotnet/api/system.string.format?view=net-5.0#how-do-i-include-literal-braces–and–in-the-result-string