JSON: получение значения из файла json в android - PullRequest
0 голосов
/ 28 февраля 2020

Общее редактирование вопроса, на предыдущий вопрос ответил @santalu, слава тебе, мужик !!

Теперь вопрос в том, что я пытаюсь получить доступ к файлу JSON, который я получаю из этой функции ниже , Я создаю приложение, чтобы перечислить все туристические места в городе с его широтой. Я могу получить доступ к json для чтения названий туристических мест, но не могу прочитать широту и долготу с json.

public void get_json_tourist_places(){
        Response responses;
        responses = null;
        /*urls="https://maps.googleapis.com/maps/api/place/textsearch/json?query="+place_name+"point+of+interest&language=en&type=tourist_attraction,museum,amusement_park,zoo"+"&key="+getString(R.string.api_key);
        */
        urls = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=new+york+city+point+of+interest&language=en&key=API_key&type=tourist_attraction,museum,amusement_park,zoo";
        try {
            Log.d("JSON", "about to retrieve data");
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(urls)
                    .build();


            try {
                responses = client.newCall(request).execute();
                jsonData = responses.body().string();
                Log.d("JSON", jsonData);
                /*return response_ztring;*/
                if (jsonData != null) {
                    Log.d("JSON", "data received");
                    JSONObject Jobject = null;
                    try {

                        Jobject = new JSONObject(jsonData);
                        Log.d("JSON", "Jobject read jsondata");

                    } catch (JSONException e) {
                        Log.d("JSON", "Jobject from jsonData error");
                        e.printStackTrace();
                    }

                    JSONArray Jarray = null;
                    try {

                        Jarray = Jobject.getJSONArray("results");
                        Log.d("JSON", "JArray read results");
                    } catch (JSONException e) {
                        Log.d("JSON", "Jobject from jsonData error");
                        e.printStackTrace();
                    }

                    if (Jarray != null) {
                        /*Jarralength = Jarray.length();*/
                        Jarralength = 19;

                        for (int i = 0; i < Jarralength; i++) {
                            try {
                                JSONObject object = Jarray.getJSONObject(i);
                                tourist_name = object.getString("name");
                                Log.d("JSON",tourist_name);
                                tourist_lat = object.getDouble("lat");
                                Log.d("JSON",Double.toString(tourist_lat));
                                tourist_lng = object.getDouble("lng");
                                tourist_latlang = new LatLng(tourist_lat,tourist_lng);
                                mMap.addMarker(new MarkerOptions().position(tourist_latlang).title(tourist_name));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }}
                }else{
                    Log.d("JSON", "Null object found");
                }


            } catch (IOException e) {
                Log.d("JSON", "inside function - error 1");
                Log.d("JSON", e.toString()+"inside function");
                /*return null;*/
            }

        }catch (Exception e){
            Log.d("JSON", "inside function - error 2");
            Log.d("JSON",e.toString()+"inside function");
            /*return null;*/
        }






    }
}

Я пытался получить данные, но android через системная ошибка. Так что я думаю, что мое решение неверно. Так как я новичок в json, пожалуйста, помогите мне. Ниже приведен логкат: -

2020-02-28 20:02:57.389 22628-22628/com.example.tripplanner3 D/JSON: The High Line
2020-02-28 20:02:57.389 22628-22628/com.example.tripplanner3 W/System.err: org.json.JSONException: No value for lat
2020-02-28 20:02:57.389 22628-22628/com.example.tripplanner3 W/System.err:     at org.json.JSONObject.get(JSONObject.java:399)
2020-02-28 20:02:57.389 22628-22628/com.example.tripplanner3 W/System.err:     at org.json.JSONObject.getDouble(JSONObject.java:454)
2020-02-28 20:02:57.389 22628-22628/com.example.tripplanner3 W/System.err:     at com.example.tripplanner3.MapsActivity.get_json_tourist_places(MapsActivity.java:173)
2020-02-28 20:02:57.390 22628-22628/com.example.tripplanner3 D/JSON: Radio City Music Hall
2020-02-28 20:02:57.390 22628-22628/com.example.tripplanner3 W/System.err: org.json.JSONException: No value for lat
2020-02-28 20:02:57.390 22628-22628/com.example.tripplanner3 W/System.err:     at org.json.JSONObject.get(JSONObject.java:399)
2020-02-28 20:02:57.390 22628-22628/com.example.tripplanner3 W/System.err:     at org.json.JSONObject.getDouble(JSONObject.java:454)
2020-02-28 20:02:57.390 22628-22628/com.example.tripplanner3 W/System.err:     at com.example.tripplanner3.MapsActivity.get_json_tourist_places(MapsActivity.java:173)
2020-02-28 20:02:57.390 22628-22628/com.example.tripplanner3 D/JSON: Statue of Liberty National Monument
2020-02-28 20:02:57.391 22628-22628/com.example.tripplanner3 W/System.err: org.json.JSONException: No value for lat
2020-02-28 20:02:57.391 22628-22628/com.example.tripplanner3 W/System.err:     at org.json.JSONObject.get(JSONObject.java:399)
2020-02-28 20:02:57.391 22628-22628/com.example.tripplanner3 W/System.err:     at org.json.JSONObject.getDouble(JSONObject.java:454)
2020-02-28 20:02:57.391 22628-22628/com.example.tripplanner3 W/System.err:     at com.example.tripplanner3.MapsActivity.get_json_tourist_places(MapsActivity.java:173)
2020-02-28 20:02:57.391 22628-22628/com.example.tripplanner3 D/JSON: The Metropolitan Museum of Art
2020-02-28 20:02:57.391 22628-22628/com.example.tripplanner3 W/System.err: org.json.JSONException: No value for lat
2020-02-28 20:02:57.391 22628-22628/com.example.tripplanner3 W/System.err:     at org.json.JSONObject.get(JSONObject.java:399)
2020-02-28 20:02:57.391 22628-22628/com.example.tripplanner3 W/System.err:     at org.json.JSONObject.getDouble(JSONObject.java:454)
2020-02-28 20:02:57.391 22628-22628/com.example.tripplanner3 W/System.err:     at com.example.tripplanner3.MapsActivity.get_json_tourist_places(MapsActivity.java:173)
2020-02-28 20:02:57.392 22628-22628/com.example.tripplanner3 D/JSON: Central Park
2020-02-28 20:02:57.392 22628-22628/com.example.tripplanner3 W/System.err: org.json.JSONException: No value for lat
2020-02-28 20:02:57.392 22628-22628/com.example.tripplanner3 W/System.err:     at org.json.JSONObject.get(JSONObject.java:399)
2020-02-28 20:02:57.392 22628-22628/com.example.tripplanner3 W/System.err:     at org.json.JSONObject.getDouble(JSONObject.java:454)
2020-02-28 20:02:57.392 22628-22628/com.example.tripplanner3 W/System.err:     at com.example.tripplanner3.MapsActivity.get_json_tourist_places(MapsActivity.java:173)
2020-02-28 20:02:57.393 22628-22628/com.example.tripplanner3 D/JSON: Empire State Building
2020-02-28 20:02:57.393 22628-22628/com.example.tripplanner3 W/System.err: org.json.JSONException: No value for lat
2020-02-28 20:02:57.393 22628-22628/com.example.tripplanner3 W/System.err:     at org.json.JSONObject.get(JSONObject.java:399)
2020-02-28 20:02:57.393 22628-22628/com.example.tripplanner3 W/System.err:     at org.json.JSONObject.getDouble(JSONObject.java:454)
2020-02-28 20:02:57.393 22628-22628/com.example.tripplanner3 W/System.err:     at com.example.tripplanner3.MapsActivity.get_json_tourist_places(MapsActivity.java:173)

Файл json, который я получаю от API, находится ниже: -

{
       "html_attributions" : [],
       "next_page_token" : "CtQERAIAAF_ny-R_r3JBJMToZ6eVAv3cu9Ang5GnRFKNDml2JnE0OmsRxDCWeO0tslc46gW6Hl65jLD-eEpcf1Zaoyhaw5LKl3dojxMqZJx48SMazCjw0V5dkMqU1r8yMfvOITUhqJvtpJGxSKlxEMRke9tN5rxnp8oG-6FGCwR1oRrx_h-zichjyKUintGJJBiDKnTXBQVIscePKScKDSKM0xxkZnX0didAm8meOA7jR7Wte6HRNn0VEslgnlpekJuhi5dAguOE-nk4UuOG6MCuSAMQxhqCYYVDxKa8QZKBv7RoElcDuoezTTCYo3yjRliEIFTfCi0vMybBvZHGmGlY5cRQMshxMsJKnnpsFrl-5zPmsUvuhPe8cVkE-isfN1WiG7uUfiDWj_bVpUp7JOKrh81aqTnW4zIEGzT6nSoS87ltXyinqlY2heVxInLoYaKpvUNaeghkTr0cGL5sdgLu1RGUKHr6zkJrDY63I51jkAOZsYaYHEEMvnSB-JUE6VTT_04Kg7JRMLO6VbEQnP3tJsbLuzRm4K7rbo07WggKYLzpgk7cMtFQpqzcTUExTiJVhmG8aBvij58s9eLbhXROoZN9gDifhBg3d-jqNPHw0-RXgHMD6blK_DxBeUwj1Ndij7ekaRLjouhTtStOWMbWkdZmfzS1XffY6ceKrAHKmacpoTH0p8QYGTw5v5WPfi-O4DOfBqFMvw60HGJX3IEBb3yqpxGnz9K5nm2qJ1W2-LxEQ-5Nn7VjbeYLCGsw9W3nE87zuagwBjPOF3RjYnfurkkF4QASEI6zwqeQiFUDF67KOq-LT-oaFOc4TT7-o5btr0CCiNFGoU3GPYAq",
       "results" : [
          {
             "formatted_address" : "New York, NY 10011, United States",
             "geometry" : {
                "location" : {
                   "lat" : 40.7479925,
                   "lng" : -74.0047649
                },
                "viewport" : {
                   "northeast" : {
                      "lat" : 40.75890824999998,
                      "lng" : -73.99853175
                   },
                   "southwest" : {
                      "lat" : 40.73287364999999,
                      "lng" : -74.01141114999999
                   }
                }
             },
             "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/generic_recreational-71.png",
             "id" : "72dc79d023feec77725d7336e7c46fee27805319",
             "name" : "The High Line",
             "opening_hours" : {
                "open_now" : true
             },
             "photos" : [
                {
                   "height" : 3267,
                   "html_attributions" : [
                      "\u003ca href=\"https://maps.google.com/maps/contrib/105487997458497097901\"\u003eАлександр Иванов\u003c/a\u003e"
                   ],
                   "photo_reference" : "CmRaAAAAMQLLPJRDK2RUdpgd5HM7cCyLO0n4JPecWoRECfD1-0tGtjtxj3kDrv4bcGVML6Ka6h6lUBuJ1qA0lfhDe_ZnLl9krJCjEr1caXLUdNpPRxgQrgdGhHKkmK6XBWlq-Nd7EhCJMH4b-vQfZ9agTO6C73AvGhQihQAwG1zkF2nZygrixAD4NOzaZw",
                   "width" : 4895
                }
             ],
             "place_id" : "ChIJ5bQPhMdZwokRkTwKhVxhP1g",
             "plus_code" : {
                "compound_code" : "PXXW+53 New York, United States",
                "global_code" : "87G7PXXW+53"
             },
             "rating" : 4.7,
             "reference" : "ChIJ5bQPhMdZwokRkTwKhVxhP1g",
             "types" : [ "park", "tourist_attraction", "point_of_interest", "establishment" ],
             "user_ratings_total" : 40128
          },
          {
             "formatted_address" : "1260 6th Ave, New York, NY 10020, United States",
             "geometry" : {
                "location" : {
                   "lat" : 40.75997599999999,
                   "lng" : -73.97997719999999
                },
                "viewport" : {
                   "northeast" : {
                      "lat" : 40.76128112989272,
                      "lng" : -73.97878962010728
                   },
                   "southwest" : {
                      "lat" : 40.75858147010728,
                      "lng" : -73.98148927989271
                   }
                }
             },
             "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
             "id" : "89dd7f0c82efc14f18954f8abf2925515037927a",
             "name" : "Radio City Music Hall",
             "photos" : [
                {
                   "height" : 2988,
                   "html_attributions" : [
                      "\u003ca href=\"https://maps.google.com/maps/contrib/116446596751419338697\"\u003eAndres Moya\u003c/a\u003e"
                   ],
                   "photo_reference" : "CmRaAAAAa2L9ceDCY9787WSlvpuvWntfsA60hBed8bquDMUaXuCCjXdvjLx5neVliD1aRJlkcdTvjElMuc_jhN0z2fYFjS9mUnACdRw-HVgVGRmpsMTFmi_dB-FG1Wx3BII3ZEOYEhBJY7yVQgUzoCwy5vh61NM1GhTy52brtjjvEgMVRTzmZ7vE0LRUlQ",
                   "width" : 5312
                }
             ],
             "place_id" : "ChIJPS8b1vhYwokRldqq2YHmxJI",

1 Ответ

1 голос
/ 28 февраля 2020

Посмотрите на JSON:

{
       ...
       "results" : [
          {
             ...
             "geometry" : {
                "location" : {
                   "lat" : 40.7479925,
                   "lng" : -74.0047649
                },

Чтобы получить lat, вам нужно пройти по этим объектам.

Вы начали, вы сделали это:

Jobject = new JSONObject(jsonData);
Jobject.getJSONArray("results");

Но вам нужно продолжать так:

Jobject.getJSONArray("results")
.getJSONObject("geometry")
.getJSONObject("location")
.getDouble("lat")

Ака что-то вроде этого:

JSONObject object = Jarray.getJSONObject(i);
tourist_name = object.getString("name");
Log.d("JSON",tourist_name);

JSONObject location = object.getJSONObject("geometry").getJSONObject("location");                                
tourist_lat = location.getDouble("lat");                                
tourist_lng = location.getDouble("lng");
Log.d("JSON", "Lat/Lng" + tourist_lat + "/" + tourist_lng);
...