Parse Json with Gson without POJO?
You are almost there and you are correct that you need to parse JsonObject
.
JsonObject body = gson.fromJson(json, JsonObject.class);JsonArray results = body.get("results").getAsJsonArray();JsonObject firstResult = results.get(0).getAsJsonObject();JsonElement address = firstResult.get("formatted_address");System.out.println(address.getAsString());
You can do it, but you do not have to use GSON necessarily.
You can parse a JSON as Java Objects with Jackson
. For example you can obtain: Object, List, Hashmap, Integer, String, etc. without POJO classes.
In android first add to gradle the following line:
implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.0.1'
next import the mapper
import com.fasterxml.jackson.databind.ObjectMapper
at last you can use the mapper passing the String JSON value, example:
HashMap<*,*> object = new ObjectMapper().readValue(body, HashMap.class);
I hope it helps you. To see more about Jackson please visit: Jackson