简体   繁体   English

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

[英]How to convert nested json into Map without typecasting using Gson

I am trying to understand/learn how to pull data from a weather API, i have successfully done that and i got a Json file filled with data.我正在尝试了解/学习如何从天气 API 中提取数据,我已经成功地做到了,我得到了一个 Json 文件,里面充满了数据。 I managed with gson put the information into a Map.我使用 gson 将信息放入 Map 进行管理。

But it also has nested json for key main were i'm pulling out value into what may by explicit typecasting.但它也有嵌套的 json 作为main的关键,我正在通过显式类型转换将值提取到可能的值中。

The thing i would like to ask, is if there is a neater way of doing this and so that i don't need to do explicit type casting nested json into Map我想问的是,是否有一种更简洁的方法可以做到这一点,这样我就不需要将嵌套的 json 显式类型转换为Map

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"));

This is my output in the console:这是我在控制台中的 output:

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

I would say you can convert the json string into Map<String, JsonElement> so that you have so methods to find nested object is JsonObject or JsonArray .我想说您可以将 json 字符串转换为Map<String, JsonElement> ,这样您就有办法找到嵌套的 object 是JsonObjectJsonArray So in the blow example main is key with JsonObject as value所以在这个例子中main是以JsonObject作为值的关键

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

You can parse the value into Map by using fromJson您可以使用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"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM