简体   繁体   English

Json-Simple,强制转换异常

[英]Json-Simple , Cast Exception

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. 运行此命令时,我org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray异常。 please help. 请帮忙。 I'm trying to print all the values inside the JSON 我正在尝试在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: 样本JSON输出如下所示:

{ "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 } {“ 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”:“赢得20个美国家庭假期”,“ description”:“部分描述”,“ expiry_date“:1383018300,​​“ brand_name”:“品牌名称”,“ store_locations”:[{” city_id“:” 46“,” country_id“:” 9“}]}},“成功”: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 如果返回的json只是一个数组,例如[“ asdf”,“ asdf”,“ asdf2”,“ basdf”],则在Java中,当您使用json-simple解析它时,它将是一个JSONArray对象

If the json returned is a json object {"key":"value", "keyArray":["asdf","asdf"]} it will parse to a JSONObject. 如果返回的json是一个json对象{“ key”:“ value”,“ keyArray”:[“ asdf”,“ asdf”]},它将解析为JSONObject。 If you get the keyArray value it will parse as a JSONArray 如果获得keyArray值,它将解析为JSONArray

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM