【问题标题】:String 'Input string was not in a correct format' exception on JSON stringJSON字符串上的字符串“输入字符串格式不正确”异常
【发布时间】:2013-11-30 03:50:14
【问题描述】:

我正在尝试将 JSON 有效负载转义为字符串。目前,我在尝试完成转换时收到“输入字符串格式不正确”异常错误。

我认为在转义字符串的开头和结尾使用双花括号可以解决它,但它没有。

代码如下:

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

谁能指导我这里哪里出错了?

【问题讨论】:

  • 你应该使用像json.netJavaScriptSerializer这样的序列化器,这样你就不用担心字符串格式了。

标签: c# json exception


【解决方案1】:

使用 string.Format,'{' 和 '}' 字符需要转义为 {{ 和 }}

string.Format("{ a: {0} }", 2); // throws exception
string.Format("{{ a: {0} }}", 2); // returns the string "{ a: 2 }"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    相关资源
    最近更新 更多