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?
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.
The only difference between Java strings and Json strings is that in Json, forward-slash (/) is escaped.
@Arashsoft: No, / has no special meaning within a JSON string. It's just / .
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\"}";
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With