Parse Json with Gson without POJO?

半世苍凉 提交于 2019-12-05 04:31:59

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!