5

I'm trying to escape a JSON payload to a string. Currently I'm receiving an 'Input string was not in a correct format' exception error when trying to complete the conversion.

I thought using double curly braces at the start and end of the escape string would solve it but it hasn't.

Here is the code:

 var newGuidIDEmployeeSyncRequest = Guid.NewGuid().ToString();

 string test = String.Format("{\"confirmMessageID\":{\"idValue\":\"{0}\"},\"createDateTime\":\"{1}\",\"requestReceiptDateTime\":\"{2}\",\"protocolCode\":{\"codeValue\":\"http\"},\"requestStatusCode\":{\"codeValue\":\"succeeded\"},\"requestMethodCode\":{\"codeValue\":\"POST\"},\"requestLink\":null,\"resourceMessages\":[{\"resourceMessageID\":{\"idValue\":\"G3R4RG61Y2T3P1QZ\"},\"resourceStatusCode\":{\"codeValue\":\"succeeded\"},\"processMessages\":[{\"userMessage\":{\"messageTxt\":\"Operation Successful for G3R4RG61Y2T3P1QZ\"}}]}]}", newGuidIDEmployeeSyncRequest, DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss"), DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss"));

Can anyone guide me on where I'm going wrong here?

1
  • You should use a serializer like json.net or JavaScriptSerializer, then you don't have to worry about string formatting. Commented Nov 29, 2013 at 19:52

1 Answer 1

18

With string.Format, the '{' and '}' characters need to be escaped as {{ and }}

string.Format("{ a: {0} }", 2); // throws exception
string.Format("{{ a: {0} }}", 2); // returns the string "{ a: 2 }"
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.