无法在Java中使用for循环获取所有JSONObjects

时间:2016-12-22 17:42:02

标签: java arrays json

首先我有两个阵列 JSONObject类型的ArrayList jsonArrayResponse,jsonArraySubResponse

注意:两个数组都具有相同的大小

这是我的代码,用于获取并将位置数据插入数组:

        for (int i = 0; i<jsonArrayResponse.size() - 1; i++) {

            try {

                JSONObject objectDictionary = jsonArrayResponse.get(i);
                JSONObject objectSubDictionary = jsonArraySubResponse.get(i);

                PlaceObject placeObject = new PlaceObject();

                placeObject.setPlace_id(objectDictionary.getString("place_id"));
                placeObject.setLat(objectDictionary.getJSONObject("geometry").getJSONObject("location").getDouble("lat"));
                placeObject.setLng(objectDictionary.getJSONObject("geometry").getJSONObject("location").getDouble("lng"));
                placeObject.setName(objectDictionary.getString("name"));

                if (objectDictionary.has("photos")) {

                    JSONObject photoReferenceObject = objectDictionary.getJSONArray("photos").getJSONObject(0);

                    if (photoReferenceObject.has("photo_reference")) {
                        placeObject.setPhotoReference(photoReferenceObject.getString("photo_reference"));
                    }
                }

                if (objectSubDictionary.has("vicinity")) {
                    placeObject.setVicinity(objectSubDictionary.getString("vicinity"));
                }

                if (objectSubDictionary.has("formatted_address")) {
                    placeObject.setFormatted_address(objectSubDictionary.getString("formatted_address"));
                }

                if (objectSubDictionary.has("formatted_phone_number")) {
                    placeObject.setFormatted_phone_number(objectSubDictionary.getString("formatted_phone_number"));
                }

                if (objectSubDictionary.has("international_phone_number")) {
                    placeObject.setInternational_phone_number(objectSubDictionary.getString("international_phone_number"));
                }

                if (objectSubDictionary.has("url")) {
                    placeObject.setUrl(objectSubDictionary.getString("url"));
                }

                if (objectSubDictionary.has("website")) {
                    placeObject.setWebsite(objectSubDictionary.getString("website"));
                }

                if (objectSubDictionary.has("reviews")) {

                    ArrayList<Reviews> reviews = new ArrayList<Reviews>();

                    for (int j = 0; j<objectSubDictionary.getJSONArray("reviews").length(); j++) {

                        Reviews reviewObject = new Reviews();
                        JSONObject review = objectSubDictionary.getJSONArray("reviews").getJSONObject(j);

                        reviewObject.setAuthor_name(review.getString("author_name"));
                        if (review.has("rating")) {
                            reviewObject.setRating(review.getString("rating"));
                        }
                        reviewObject.setText(review.getString("text"));
                        if (review.has("type")) {
                            reviewObject.setType(review.getString("type"));
                        }

                        reviews.add(reviewObject);
                    }

                    placeObject.setReviews(reviews);
                }

                if (objectDictionary.has("opening_hours")) {

                    ArrayList<String> days = new ArrayList<String>();

                    for (int z = 0; z<objectDictionary.getJSONObject("opening_hours").getJSONArray("reviews").length(); z++) {

                        String day = objectDictionary.getJSONObject("opening_hours").getJSONArray("reviews").getString(z);
                        days.add(day);
                    }

                    placeObject.setWeekday_text(days);
                }

                if (objectDictionary.has("opening_hours")) {
                    if (objectDictionary.getJSONObject("opening_hours").has("open_now")) {

                        placeObject.setOpen_now(objectDictionary.getJSONObject("opening_hours").getBoolean("open_now"));
                    }
                }

                Float distanceInKilometers = distance(objectDictionary.getJSONObject("geometry").getJSONObject("location").getDouble("lat"), objectDictionary.getJSONObject("geometry").getJSONObject("location").getDouble("lng"), Global.loc.getLatitude(), Global.loc.getLongitude()) / 1000;

                placeObject.setDistance(distanceInKilometers.doubleValue());

                if (objectDictionary.has("rating")) {
                    placeObject.setRating(objectDictionary.getDouble("rating"));
                }

                if (objectDictionary.has("price_level")) {
                    placeObject.setPrice_level(objectDictionary.getInt("price_level"));
                }

                placeObjects.add(placeObject);

                if (i == jsonArrayResponse.size() - 1) {
                    this.placeObjectsResopones = placeObjects;
                    this.placeObjects = placeObjects;
                }
            } catch (JSONException  e) {
                e.printStackTrace();
            }
        }

示例Json数据:

1)地方搜索请求:

{
   "html_attributions" : [],
   "results" : [
      {
         "geometry" : {
            "location" : {
               "lat" : -33.870775,
               "lng" : 151.199025
            }
         },
         "icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/travel_agent-71.png",
         "id" : "21a0b251c9b8392186142c798263e289fe45b4aa",
         "name" : "Rhythmboat Cruises",
         "opening_hours" : {
            "open_now" : true
         },
         "photos" : [
            {
               "height" : 270,
               "html_attributions" : [],
               "photo_reference" : "CnRnAAAAF-LjFR1ZV93eawe1cU_3QNMCNmaGkowY7CnOf-kcNmPhNnPEG9W979jOuJJ1sGr75rhD5hqKzjD8vbMbSsRnq_Ni3ZIGfY6hKWmsOf3qHKJInkm4h55lzvLAXJVc-Rr4kI9O1tmIblblUpg2oqoq8RIQRMQJhFsTr5s9haxQ07EQHxoUO0ICubVFGYfJiMUPor1GnIWb5i8",
               "width" : 519
            }
         ],
         "place_id" : "ChIJyWEHuEmuEmsRm9hTkapTCrk",
         "scope" : "GOOGLE",
         "alt_ids" : [
            {
               "place_id" : "D9iJyWEHuEmuEmsRm9hTkapTCrk",
               "scope" : "APP"
            }
         ],
         "reference" : "CoQBdQAAAFSiijw5-cAV68xdf2O18pKIZ0seJh03u9h9wk_lEdG-cP1dWvp_QGS4SNCBMk_fB06YRsfMrNkINtPez22p5lRIlj5ty_HmcNwcl6GZXbD2RdXsVfLYlQwnZQcnu7ihkjZp_2gk1-fWXql3GQ8-1BEGwgCxG-eaSnIJIBPuIpihEhAY1WYdxPvOWsPnb2-nGb6QGhTipN0lgaLpQTnkcMeAIEvCsSa0Ww",
         "types" : [ "travel_agency", "restaurant", "food", "establishment" ],
         "vicinity" : "Pyrmont Bay Wharf Darling Dr, Sydney"
      },...
   ],
   "status" : "OK"
}

2)地方详情请求:

{
   "html_attributions" : [],
   "result" : {
      "address_components" : [
         {
            "long_name" : "48",
            "short_name" : "48",
            "types" : [ "street_number" ]
         },
         {
            "long_name" : "Pirrama Road",
            "short_name" : "Pirrama Road",
            "types" : [ "route" ]
         },
         {
            "long_name" : "Pyrmont",
            "short_name" : "Pyrmont",
            "types" : [ "locality", "political" ]
         },
         {
            "long_name" : "NSW",
            "short_name" : "NSW",
            "types" : [ "administrative_area_level_1", "political" ]
         },
         {
            "long_name" : "AU",
            "short_name" : "AU",
            "types" : [ "country", "political" ]
         },
         {
            "long_name" : "2009",
            "short_name" : "2009",
            "types" : [ "postal_code" ]
         }
      ],
      "formatted_address" : "48 Pirrama Road, Pyrmont NSW, Australia",
      "formatted_phone_number" : "(02) 9374 4000",
      "geometry" : {
         "location" : {
           "lat" : -33.8669710,
           "lng" : 151.1958750
         },
         "viewport" : {
            "northeast" : {
               "lat" : -33.8665053,
               "lng" : 151.1960371
            },
            "southwest" : {
               "lat" : -33.8669293,
               "lng" : 151.1952183
            }
         }
      },
      "icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
      "id" : "4f89212bf76dde31f092cfc14d7506555d85b5c7",
      "international_phone_number" : "+61 2 9374 4000",
      "name" : "Google Sydney",
      "place_id" : "ChIJN1t_tDeuEmsRUsoyG83frY4",
      "scope" : "GOOGLE",
      "alt_ids" : [
         {
            "place_id" : "D9iJyWEHuEmuEmsRm9hTkapTCrk",
            "scope" : "APP"
         }
      ],
      "rating" : 4.70,
      "reference" : "CnRsAAAA98C4wD-VFvzGq-KHVEFhlHuy1TD1W6UYZw7KjuvfVsKMRZkbCVBVDxXFOOCM108n9PuJMJxeAxix3WB6B16c1p2bY1ZQyOrcu1d9247xQhUmPgYjN37JMo5QBsWipTsnoIZA9yAzA-0pnxFM6yAcDhIQbU0z05f3xD3m9NQnhEDjvBoUw-BdcocVpXzKFcnMXUpf-nkyF1w",
      "reviews" : [
         {
            "aspects" : [
               {
                  "rating" : 3,
                  "type" : "quality"
               }
            ],
            "author_name" : "Simon Bengtsson",
            "author_url" : "https://plus.google.com/104675092887960962573",
            "language" : "en",
            "rating" : 5,
            "text" : "Just went inside to have a look at Google. Amazing.",
            "time" : 1338440552869
         },
         {
           "aspects" : [
              {
                 "rating" : 3,
                 "type" : "quality"
              }
             ],
            "author_name" : "Felix Rauch Valenti",
            "author_url" : "https://plus.google.com/103291556674373289857",
            "language" : "en",
            "rating" : 5,
            "text" : "Best place to work :-)",
            "time" : 1338411244325
         },
         {
           "aspects" : [
              {
                 "rating" : 3,
                 "type" : "quality"
              }
             ],
            "author_name" : "Chris",
            "language" : "en",
            "rating" : 5,
            "text" : "Great place to work, always lots of free food!",
            "time" : 1330467089039
         }
      ],
      "types" : [ "establishment" ],
      "url" : "http://maps.google.com/maps/place?cid=10281119596374313554",
      "vicinity" : "48 Pirrama Road, Pyrmont",
      "website" : "http://www.google.com.au/"
   },
   "status" : "OK"
}

我的问题是我弄乱了数据,我认为如果数据需要时间来处理它会跳过。如何改进它以确保我获得一个位置对象的所有数据?

2 个答案:

答案 0 :(得分:1)

我注意到了

在你的循环中这种情况不会发生

if (i == jsonArrayResponse.size() - 1) {
 ...
}

因为你的循环不会继续,直到i == jsonArrayResponse.size() - 1

尝试在循环行中添加=,如此

for (int i = 0; i <= jsonArrayResponse.size() - 1; i++) { ...}

也许这就是缺少数组中最后一个元素的原因

答案 1 :(得分:0)

请提供样本数据。我会尝试使用GSON。