如何在不使用 Gson 进行类型转换的情况下将嵌套 json 转换为 Map

How to convert nested json into Map without typecasting using Gson

我正在尝试 understand/learn 如何从天气 API 中提取数据,我已经成功地做到了,并且我得到了一个充满数据的 Json 文件。我用 gson 管理将信息放入地图中。

但它也嵌套了 json 键 main 是我通过显式类型转换将值提取到可能的内容中。

我想问的是,是否有更简洁的方法,这样我就不需要将 json 嵌套到 Map[= 的显式类型转换15=]

Map<String, Object> resultMap = new Gson().fromJson(jsonString, new TypeToken<HashMap<String, Object>>() {
            }.getType());

            for (Map.Entry<String, Object> entry : resultMap.entrySet()) {
                System.out.println(entry);
            }

            System.out.println(resultMap.get("temp"));
            Map<String, Object> mainMap = (Map<String, Object>) resultMap.get("main");
            System.out.println("Temp: " + mainMap.get("temp"));

这是我在控制台中的输出:

rain={}
visibility=10000.0
timezone=7200.0
main={temp=8.1, pressure=1007.0, humidity=93.0, temp_min=7.0, temp_max=10.0}
clouds={all=75.0}
sys={type=1.0, id=1788.0, country=SE, sunrise=1.571203601E9, sunset=1.571240388E9}
dt=1.571249075E9
coord={lon=18.06, lat=59.33}
weather=[{id=301.0, main=Drizzle, description=drizzle, icon=09n}]
name=Stockholm
cod=200.0
id=2673730.0
base=stations
wind={speed=3.6, deg=40.0}
null
Temp: 8.1

我会说你可以将 json 字符串转换成 Map<String, JsonElement> 这样你就可以找到嵌套对象的方法是 JsonObjectJsonArray。所以在下面的例子中 main 是键 JsonObject 作为值

main: {
        temp:8.1, 
        pressure:1007.0, 
        humidity=93.0, 
        temp_min=7.0, 
        temp_max=10.0
      }

您可以使用 fromJson

将值解析为 Map
Map<String, Object> resultMap = new Gson().fromJson(jsonString, new TypeToken<Map<String, Object>>() {
        }.getType());

        for (Map.Entry<String, Object> entry : resultMap.entrySet()) {
            System.out.println(entry);
        }

        System.out.println(resultMap.get("temp"));
        Map<String, Object> mainMap = new Gson().fromJson(resultMap.get("main").toString(), new TypeToken<Map<String, Object>>() {
        }.getType());
        System.out.println("Temp: " + mainMap.get("temp"));