问题
I am trying to convert a json string to JSONArray of org.json.JSONArray class, the string contains a dateformat with forward slah, but I am getting the following exception because of the slash included in string.
public static void main(String args[]) throws JSONException{
String jsonString = "[{ID:1, Name:Ann, DOB:14/08/1991}, {ID:2, Name:Vann, DOB:14/08/1992}]";
JSONArray jsonArray = new JSONArray(jsonString);
System.out.println(jsonArray.toString());
}
Exception in thread "main" org.json.JSONException: Expected a ',' or '}' at 25 [character 26 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:451)
at org.json.JSONObject.<init>(JSONObject.java:230)
at org.json.JSONTokener.nextValue(JSONTokener.java:380)
at org.json.JSONArray.<init>(JSONArray.java:118)
at org.json.JSONArray.<init>(JSONArray.java:147)
at com.s4m.sftp.service.impl.SFTPServiceImpl.main(SFTPServiceImpl.java:1150)
回答1:
String values in JSON
Strings should be quoted... including the attribute names. See the JSON specification:
An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string.
The representation of strings is similar to conventions used in the C family of programming languages. A string begins and ends with quotation marks.
Date values in JSON
JSON has no representation for date
type. It must be represented as a string. See this answer for more information.
Online JSON validator
You can use online JSON validators to check the validity.
Valid JSON
[
{
"ID":1,
"Name":"Ann",
"DOB":"14/08/1991"
},
{
"ID":2,
"Name":"Vann",
"DOB":"14/08/1992"
}
]
However, I would use the format yyyy-mm-dd
for date values instead of dd/mm/yyyy
.
Valid JSON as Java String
String jsonString =
"[{\"ID\":1,\"Name\":\"Ann\",\"DOB\":\"14/08/1991\"},{\"ID\":2,\"Name\":\"Vann\",\"DOB\":\"14/08/1992\"}]";
回答2:
Strings should be wrapped in double quotes.
try with the below JSON string
[{"ID":1, "Name":"Ann", "DOB":"14/08/1991"}, {"ID":2, "Name":"Vann", "DOB":"14/08/1992"}]
Maintain the type as string for all fields . Use toString to convert or just send an RFC 1123 date string ToString("r") to parse
来源:https://stackoverflow.com/questions/54436406/string-to-jsonarray-giving-exception-because-of-slash-in-string