Shaiju Janardhanan Shaiju Janardhanan - 3 months ago 8
JSON Question

String.format throws incorrect format exception when there is an extra } in the string. What is the best way to resolve this?

String.format throws incorrect format exception when there is an extra } in the string as shown in the snippet below

var input = "1";
var data = string.Format(@"{0}}", input);


I was able to resolve the issue by adding an extra } as shown below

var data = string.Format(@"{0}}}", input);


However I need to know if there is any better solution to this issue

Answer

I would highly recommend using C# 6 String Interpolation feature as it is more readable and maintainable:

var data = $"{{{input}}}";

When the string grows large, you'll see the benefit of Visual Studio formatting and coloring your string like this:

enter image description here

Comments