Domanda

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"));
È stato utile?

Soluzione

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();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top