please find my code below. When I run this I'm getting org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray
exception. please help. I'm trying to print all the values inside the JSON
public static void main(String[] args) throws Exception {
URL website = new URL("http://MY_TESTING_SITE");
URLConnection connection = website.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
JSONParser parser = new JSONParser();
Object obj = parser.parse(response.toString());
JSONObject jsonObject = (JSONObject) obj;
System.out.println(jsonObject.get("data")); //Works fine till here and get proper output
JSONArray msg = (JSONArray) jsonObject.get("data");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
The sample JSON Output looks like the one shown below:
{ "tsNow": 1376325485, "data": { "1352": { "for_loyal": "1", "offer_image": "http://MY_IMAGE.jpg", "status": "1", "brand_id": "22", "id": "1352", "brand_image": "http://MY_BRAND_IMAGE.png", "title": "Win 20 Family Holidays to USA", "description": "Some description ", "expiry_date": 1383018300, "brand_name": "BRAND NAME", "store_locations": [ { "city_id": "46", "country_id": "9" } ] } }, "success": true }
If the json returned is only an array ie ["asdf", "asdf", "asdf2", "basdf"] then in java when you parse it with json-simple it will be a JSONArray object
If the json returned is a json object {"key":"value", "keyArray":["asdf","asdf"]} it will parse to a JSONObject. If you get the keyArray value it will parse as a JSONArray