I've a JSON Array:
JSON_STRING = [{"name": "adminparking1", "id": 1},{"name": "adminparking2", "id": 2}]
And I Want to parse it to a JSON-simple Array and work with json Objects that it provides from it examples I do it this way:
JSONParser jsonParser = new JSONParser();
Object res_obj = jsonParser.parse(JSON_STRING);
JSONArray json = (JSONArray) res_obj; //(HERE Error Occurs)
It gives me this error:
java.lang.ClassCastException: java.lang.String cannot be cast to org.json.simple.JSONArray
how can i get rid of this error?
Have you tried this:
JSONArray arr = new JSONArray(JSON_STRING);
//loop through each object
for (int i=0; i<arr.length(); i++){
JSONObject jsonProductObject = arr.getJSONObject(i);
String name = jsonProductObject.getString("name");
String url = jsonProductObject.getString("id");
}
This code works just fine, if JSON string is valid
public static void main() throws ParseException {
String JSON_STRING = "[{\"name\": \"adminparking1\", \"id\": 1},{\"name\": \"adminparking2\", \"id\": 2}]";
JSONParser jsonParser = new JSONParser();
Object res_obj = jsonParser.parse(JSON_STRING);
JSONArray json = (JSONArray) res_obj; // no Error
System.out.println(json.get(1));
}
prints
{"name":"adminparking2","id":2}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.