Gson 有没有办法检索子 JSON 对象信息而不必为它们创建自定义 类?

Is there a way with Gson to retrieve sub JSON object information without having to create custom classes for them?

我正在使用 Retrofit 和 Gson 来获取 Json 并从 OpenWeatherMap API 转换数据,我希望有一种方法可以省略编写 sub-类 对于每个嵌套对象。

关于您对这段代码的看法:

我的目标是启用直接访问属性

看到这个你会不会对着显示器尖叫,好吗

class PlaceWeatherInfo(
    val id: Long,
    val name: String,
    private val weather: List<Weather>,
    private val wind: Wind,
    @SerializedName("coord") val latLng: LatLng,
    @SerializedName("dt") val time : Long,
    @SerializedName("main") private val mainInfo: MainInfo,
    @SerializedName("sys") private val countryInfo: Country
){
    val weatherType   get() = weather[0].type 
    val description   get() = weather[0].description
    val temp          get() = mainInfo.temp
    val minTemp       get() = mainInfo.minTemp
    val maxTemp       get() = mainInfo.maxTemp
    val feelsLikeTemp get() = mainInfo.feelsLike
    val pressure      get() = mainInfo.pressure
    val humidity      get() = mainInfo.humidity
    val windSpeed     get() = wind.speed
    val windDegree    get() = wind.degree
    val country       get() = countryInfo.country
    val sunrise       get() = countryInfo.sunrise
    val sunset        get() = countryInfo.sunset

}

只是想让你知道我是 android 开发的新手,对 Gson 没有太多经验。

json其实就是HashMap或者ArrayList

一层层慢慢看

例如(通过firebase):

    public static void getCourse_class(){
    DatabaseReference database_course = FirebaseDatabase.getInstance().getReference("course").child("0001");
    database.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            for(DataSnapshot ds :dataSnapshot.getChildren()){ 
              HashMap<String,Objest> hashmap = ds.getKey();
              String s = hashmap.get("coord").get("dt").get("main").get("sys");

            }
         }
      }
    }

我建议你总是使用 "JSON To Kotlin Class ​(JsonToKotlinClass)​" 插件来处理这些东西: (切勿从 JSON 手动创建 类)

Link 插件: https://plugins.jetbrains.com/plugin/9960-json-to-kotlin-class-jsontokotlinclass-/

演示: