【问题标题】:Json-Simple , Cast ExceptionJson-Simple , 转换异常
【发布时间】:2013-08-13 00:43:15
【问题描述】:

请在下面找到我的代码。当我运行它时,我得到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": "赢得 20 次美国家庭假期", "description": "一些描述", “到期日期”:1383018300, "brand_name": "品牌名称", “商店位置”:[ { "city_id": "46", “country_id”:“9” } ] } }, “成功”:真 }

【问题讨论】:

  • 你能放一些你想提取的JSON吗?
  • “数据”属性的内容是什么?

标签: java json json-simple


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2014-04-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2017-03-24
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多