6

JSON response value looks like this "types" : [ "sublocality", "political" ]. How to get the first value of the types or how to get the word sublocality?

6
  • 1
    It's not a valid JSON. Are you sure it doesn't contain curly braces: {}? Commented Feb 5, 2013 at 13:44
  • @NikitaBeloglazov see this link maps.googleapis.com/maps/api/geocode/… Commented Feb 5, 2013 at 13:49
  • @NikitaBeloglazov it's a JSON array. Commented Feb 5, 2013 at 13:51
  • @DoctororDrive how to get these values. Commented Feb 5, 2013 at 13:59
  • 3
    @DoctororDrive it's not. It's a part of jsong object but not valid json :) Commented Feb 5, 2013 at 14:10

3 Answers 3

16
String string = yourjson;

JSONObject o = new JSONObject(yourjson);
JSONArray a = o.getJSONArray("types");
for (int i = 0; i < a.length(); i++) {
    Log.d("Type", a.getString(i));
}

This would be correct if you were parsing only the line you provided above. Note that to access types from GoogleMaps geocode you should get an array of results, than address_components, then you can access object components.getJSONObject(index).

This is a simple implementation that parses only formatted_address - what I needed in my project.

private void parseJson(List<Address> address, int maxResults, byte[] data)
{
    try {
        String json = new String(data, "UTF-8");
        JSONObject o = new JSONObject(json);
        String status = o.getString("status");
        if (status.equals(STATUS_OK)) {

            JSONArray a = o.getJSONArray("results");

            for (int i = 0; i < maxResults && i < a.length(); i++) {
                Address current = new Address(Locale.getDefault());
                JSONObject item = a.getJSONObject(i);

                current.setFeatureName(item.getString("formatted_address"));
                JSONObject location = item.getJSONObject("geometry")
                        .getJSONObject("location");
                current.setLatitude(location.getDouble("lat"));
                current.setLongitude(location.getDouble("lng"));

                address.add(current);
            }

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

}
Sign up to request clarification or add additional context in comments.

Comments

1

You should parse that JSON to get those values. You can either use JSONObject and JSONArray classes in Android or use a library like Google GSON to get the POJOs from JSON.

Comments

1

I would insist you to use GSON. I had created a demo for parsing the same map response. You can find the complete demo here. Also I had created a global GSON parser class that can be used to parse any response that is in JSON with ease.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.