1

JSON data is

"participant": {"id": "1"},

I tried the following code.But I got a exception

String.Format(("\n\"{0}\":{\"{1}\":\"{2}\"}","participant","id","1"));

Exception is

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

4
  • 5
    Escape your curly braces Commented Oct 23, 2014 at 8:14
  • You should include the exception within your question. Commented Oct 23, 2014 at 8:18
  • @ Jason Goemaat Can u please write your correction please. Commented Oct 23, 2014 at 8:18
  • What are you trying to do? Calling string.Format with no placeholders is pointless. Commented Oct 23, 2014 at 8:21

1 Answer 1

5

When you have curly braces in a string.Format call, you need to escape them using double curly braces.

For example:

var str = string.Format("\"{0}\": {{ \"id\": \"{1}\" }}", "participant", 5);

In string.Format, you use placeholders which are numerically ordered from 0 (zero) to whatever you need. These are placed in single curly braces, hence the need to escape your json curly braces.

Another option would be to use one of the many Json libraries to do the serialization for you, for example Json.NET (http://james.newtonking.com/json)

eg.

var anon = new { participant = "bob", id = 5 };
var json = JsonConvert.SerializeObject(anon);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.