2

I need to access only the value of "formatted_address" : "4 Place du Louvre, 75001 Paris, France" attribute. Please help me how to do this with com.google.gson.Gson and java Without maintaining seperate POJO class for the entire structure.

{
    "results": [{
        "address_components": [{
            "long_name": "4",
            "short_name": "4",
            "types": ["street_number"]
        }, {
            "long_name": "Place du Louvre",
            "short_name": "Place du Louvre",
            "types": ["route"]
        }, {
            "long_name": "Paris",
            "short_name": "Paris",
            "types": ["locality", "political"]
        }, {
            "long_name": "Paris",
            "short_name": "75",
            "types": ["administrative_area_level_2", "political"]
        }, {
            "long_name": "Île-de-France",
            "short_name": "IDF",
            "types": ["administrative_area_level_1", "political"]
        }, {
            "long_name": "France",
            "short_name": "FR",
            "types": ["country", "political"]
        }, {
            "long_name": "75001",
            "short_name": "75001",
            "types": ["postal_code"]
        }],
        "formatted_address": "4 Place du Louvre, 75001 Paris, France",
        "geometry": {
            "location": {
                "lat": 48.8600425,
                "lng": 2.3412674
            },
            "location_type": "ROOFTOP",
            "viewport": {
                "northeast": {
                    "lat": 48.86139148029149,
                    "lng": 2.342616380291502
                },
                "southwest": {
                    "lat": 48.8586935197085,
                    "lng": 2.339918419708498
                }
            }
        },
        "types": ["street_address"]
    }],
    "status": "OK"
}

I am expecting a solution as below but with gson.

final JSONObject jso = results.getJSONObject(i);
formattedAddress = jso.getString("formatted_address"));
1
  • Can you show us what you have tried that didn't work, so we can point out where you went wrong? Commented Apr 29, 2014 at 8:02

1 Answer 1

7

To parse a String into Json element and get an object structure

JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();

To get an object, use:

JsonObject anObject = jobject.getAsJsonObject("object_name");

To get an array, use:

JsonArray jarray = anObject.getAsJsonArray("array_name");

To get a String value, use:

String result = anObject.get("property_name").toString();
Sign up to request clarification or add additional context in comments.

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.