【问题标题】:Unable to get all JSONObjects using for loop in Java无法在 Java 中使用 for 循环获取所有 JSONObject
【发布时间】:2016-12-26 07:21:53
【问题描述】:

首先我有两个数组 JSONObject jsonArrayResponse, jsonArraySubResponse 类型的 ArrayList

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

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

        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"
}

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

【问题讨论】:

    标签: java arrays json


    【解决方案1】:

    我注意到了

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

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

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

    尝试像这样在循环行中添加 =

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

    这可能是数组中缺少最后一个元素的原因

    【讨论】:

    • 我只得到一个保存在索引 0 的对象
    • 你知道如何在后台运行这个操作然后让完成处理程序拥有一个包含所有对象的数组吗?
    • 要在后台运行这个操作,你可以使用AsyncTask,这里有一篇关于后台运行任务的好文章,androidresearch.wordpress.com/2012/03/17/…
    【解决方案2】:

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

    【讨论】:

    • 我添加了示例 json 数据
    • 从数据看来,你需要加入这2个jsons。可能是数据未排序。所以尝试根据搜索细节中的几何经纬度来加入它以放置细节。
    • 我已经通过从地点搜索中获取地点 id 来获取地点详细信息,这意味着两个请求都有数据,但将它们插入到 PlaceObject 中,数组会导致 PlaceObject 中的数据混乱
    猜你喜欢
    • 2021-09-07
    • 1970-01-01
    • 2021-08-20
    • 2023-03-31
    • 1970-01-01
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    相关资源
    最近更新 更多