【问题标题】:Parsing Through JSON Object From Retrofit Response从改造响应中解析 JSON 对象
【发布时间】:2021-12-09 13:32:00
【问题描述】:

我是 android dev 的新手,我首先制作了一个天气应用程序,它显示了 holly 预报和当前预报。我想添加一个按钮,允许用户查看每日预测,但从 API 调用来看,它看起来像是返回一个 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) {
            }
        });
    }

【问题讨论】:

  • 只是补充一下,因为我想我遗漏了一些信息。我需要进入 Day{},但我需要获取一个列表,以便我可以将它附加到一个 recyclerView。我要么是走错了路,要么是这太令人沮丧了。

标签: java android json retrofit


【解决方案1】:

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

这篇文章解释说,

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

【讨论】:

  • 解决方案非常简单。我使用了 jsonschema2pojo,但由于某种原因,我忘记了我可以创建一个自定义类。谢谢提醒。
  • 很高兴它成功了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-26
  • 2015-08-18
  • 2021-03-15
  • 1970-01-01
相关资源
最近更新 更多