0

请在下面找到我的代码。当我运行它时,我遇到了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 ”,“title”:“Win 20 Family Holidays to USA”,“description”:“一些描述”,“ expiry_date": 1383018300, "brand_name": "BRAND NAME", "store_locations": [ { "city_id": "46","country_id": "9" } ] } }, "success": true }

4

1 回答 1

0

如果返回的 json 只是一个数组,即 ["asdf", "asdf", "asdf2", "basdf"] 那么在 java 中,当您使用 json-simple 解析它时,它将是一个 JSONArray 对象

如果返回的 json 是一个 json 对象 {"key":"value", "keyArray":["asdf","asdf"]} 它将解析为一个 JSONObject。如果您获得 keyArray 值,它将被解析为 JSONArray

于 2013-08-12T14:19:44.470 回答