通过改造响应中的 JSON 个对象进行解析

Parsing Through JSON Object From Retrofit Response

我是 android 开发人员的新手,我首先制作了一个天气应用程序,它显示 horly 预报和当前预报。我想添加一个允许用户查看每日预报的按钮,但从 API 调用来看,它看起来像是 returns 一个 JSON 对象。几天来我一直坚持这个,我不知道该怎么做。

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.weatherapi.com/v1/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        APICall apiCall = retrofit.create(APICall.class);
        Call<WeatherModel> call = apiCall.getHourAndAstroDetails(latlong, "7");
        System.out.println(call.request().url());
        call.enqueue(new Callback<WeatherModel>() {
            @Override
            public void onResponse(Call<WeatherModel> call, Response<WeatherModel> response) {
                if (days == 1) {
                    weatherList = response.body().getForecast().getForecastday().get(0).getHour();
                    System.out.println("this is the size of weatherList" + weatherList.size());
                    setAdapter(weatherList);
                } else if (days == 7) {
                    dailyForcast = response.body().getForecast().getForecastday().get(0).getDay();
                }


                String sunriseTime = response.body().getForecast().getForecastday().get(0).getAstro().getSunrise();
                String sunsetTime = response.body().getForecast().getForecastday().get(0).getAstro().getSunset();
                sunriseTextView.setText(sunriseTime);
                sunsetTextView.setText(sunsetTime);
            }

            @Override
            public void onFailure(Call<WeatherModel> call, Throwable t) {
            }
        });
    }

我认为您应该为从 api 获得的所有数据创建一个模型 class,这样您就可以更轻松地处理数据。

这篇文章解释说,

https://medium.com/swlh/basic-usage-of-retrofit-in-kotlin-for-fetching-json-8b9d37999058