请在下面找到我的代码。当我运行这个时,我得到org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray
异常。请帮忙。我正在尝试打印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());
}
}
示例JSON输出如下所示:
{ “tsNow”:1376325485, “数据”:{ “1352”:{ “for_loyal”:“1”, “offer_image”:“http://MY_IMAGE.jpg”, “状态”:“1”, “brand_id”:“22”, “id”:“1352”, “brand_image”:“http://MY_BRAND_IMAGE.png”, “标题”:“赢得20个美国家庭假期”, “description”:“一些描述”, “expiry_date”:1383018300, “brand_name”:“品牌名称”, “store_locations”:[ { “city_id”:“46”, “country_id”:“9” } ] } }, “成功”:是的 }
答案 0 :(得分:0)
如果返回的json只是一个数组,即[“asdf”,“asdf”,“asdf2”,“basdf”] 然后在java中用json-simple解析它时它将是一个JSONArray对象
如果返回的json是json对象{“key”:“value”,“keyArray”:[“asdf”,“asdf”]} 它将解析为JSONObject。如果你得到keyArray值,它将解析为JSONArray