Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

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?

like image 256
user2475664 Avatar asked Jun 11 '13 18:06

user2475664


People also ask

Can JSON string contain colon?

JSON name-value pairs exampleName-value pairs have a colon between them as in "name" : "value" . JSON names are on the left side of the colon. They need to be wrapped in double quotation marks, as in “name” and can be any valid string.

How do I escape a string in JSON?

The only difference between Java strings and Json strings is that in Json, forward-slash (/) is escaped.

Is Colon a special character in JSON?

@Arashsoft: No, / has no special meaning within a JSON string. It's just / .


2 Answers

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\"}";
like image 92
willwest Avatar answered Sep 18 '22 13:09

willwest


Strings are required to be quoted in JSON:

string
  ""
  " chars "

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

like image 45
Thorn G Avatar answered Sep 17 '22 13:09

Thorn G