java 如何在 JSON 字符串中的日期时间值中转义冒号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17050807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:48:57  来源:igfitidea点击:

How to escape a colon inside a datetime value in a JSON string

javajsondatetime

提问by user2475664

I need to instantiate a JSONObject with a string that I receive from an external source. The string contains a datetime value, which in turn contains a colon. When I try to create an instance of the JSONObject, I get an error, it looks like JSON does not like the colon in the middle of the date time value.

我需要使用从外部源接收的字符串实例化 JSONObject。该字符串包含一个日期时间值,该值又包含一个冒号。当我尝试创建 JSONObject 的实例时,出现错误,看起来 JSON 不喜欢日期时间值中间的冒号。

Here is a code snippet:

这是一个代码片段:

@Test
public void testGetDate()
{
    String jsonStr = "{\"sDate\":2013-06-15T09:30:09+0000}";
    try
    {
        JSONObject jsonObject = new JSONObject(jsonStr);
        System.out.println(jsonObject.get("sDate"));

    } catch (JSONException e)
    {
        e.printStackTrace();
    }
}

The error I get is:

我得到的错误是:

org.json.JSONException: Expected a ',' or '}' at 23 [character 24 line 1]

Has anyone encountered this ? Is there some way to escape the colon?

有没有人遇到过这个?有没有办法摆脱结肠?

采纳答案by willwest

If you surround your date/time object in double quotes, it should accept it.

如果您用双引号将日期/时间对象括起来,它应该接受它。

This should work:

这应该有效:

String jsonStr = "{\"sDate\":\"2013-06-15T09:30:09+0000\"}";

回答by Tom G

Strings are required to be quoted in JSON:

字符串需要在 JSON 中引用

string
  ""
  " chars "

Your snippet is invalid, which is why the exception is thrown. You must surround the string value with double quotes.

您的代码段无效,这就是抛出异常的原因。您必须用双引号将字符串值括起来。

回答by arntg

The more interesting issue is for cases where the string is unknown. In case the format is known then it's reasonably easy to fix. Added as a utility to org.json here.

更有趣的问题是字符串未知的情况。如果格式已知,则修复起来相当容易。在此处添加为 org.json 的实用程序。