简体   繁体   中英

Extracting STATUS code of Google Places API response

I am new to using JSON and I am having an issue figuring out how to extract the STATUS code from Google Places API response. I guess the issue is because it is a seperate root element from the results array. Here is my code for my parser:

public class PlaceJSONParser {

/** Receives a JSONObject and returns a list */
public List<HashMap<String,String>> parse(JSONObject jObject){

    JSONArray jPlaces = null;
    try {
        /** Retrieves all the elements in the 'places' array */
        jPlaces = jObject.getJSONArray("results");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    /** Invoking getPlaces with the array of json object
    * where each json object represent a place
    */
    return getPlaces(jPlaces);
}

private List<HashMap<String, String>> getPlaces(JSONArray jPlaces){
    int placesCount = jPlaces.length();
    List<HashMap<String, String>> placesList = new ArrayList<HashMap<String,String>>();
    HashMap<String, String> place = null;

    /** Taking each place, parses and adds to list object */
    for(int i=0; i<placesCount;i++){
        try {
            /** Call getPlace with place JSON object to parse the place */
            place = getPlace((JSONObject)jPlaces.get(i));
            placesList.add(place);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return placesList;
}

/** Parsing the Place JSON object */
private HashMap<String, String> getPlace(JSONObject jPlace){

    HashMap<String, String> place = new HashMap<String, String>();
    String placeName = "-NA-";
    String vicinity="-NA-";
    String latitude="";
    String longitude="";

    try {
        // Extracting Place name, if available
        if(!jPlace.isNull("name")){
            placeName = jPlace.getString("name");
        }

        // Extracting Place Vicinity, if available
        if(!jPlace.isNull("vicinity")){
            vicinity = jPlace.getString("vicinity");
        }

        latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
        longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");

        place.put("place_name", placeName);
        place.put("vicinity", vicinity);
        place.put("lat", latitude);
        place.put("lng", longitude);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return place;
}
}

Yes, status, results and html_attributions are the 3 root elements in google places api JSON response. You can extract the status data from the response like below:

String statuscheck = jObject.getString("status");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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