【问题标题】:Missing JSON Array with RetroFit 2.0 & WorldWeatherOnline APIRetroFit 2.0 和 WorldWeatherOnline API 缺少 JSON 数组
【发布时间】:2023-03-23 07:23:01
【问题描述】:

我从天气 API 中提取数据,当我将完整的 url 放入浏览器时,我得到了所有数据,结构如下:

{  
   "data":{  
      "current_condition":[  
         {  
            "cloudcover":"75",
            "FeelsLikeC":"0",
            "FeelsLikeF":"32",
            "humidity":"87",
            "observation_time":"10:29 PM",
            "precipMM":"0.0",
            "pressure":"1021",
            "temp_C":"4",
            "temp_F":"39",
            "visibility":"10",
            "weatherCode":"116",
            "weatherDesc":[  
               {  
                  "value":"Partly Cloudy"
               }
            ],
            "weatherIconUrl":[  
               {  
                  "value":"http:\/\/cdn.worldweatheronline.net\/images\/wsymbols01_png_64\/wsymbol_0004_black_low_cloud.png"
               }
            ],
            "winddir16Point":"SSW",
            "winddirDegree":"210",
            "windspeedKmph":"20",
            "windspeedMiles":"13"
         }
      ],
      "request":[  
         {  }
      ],
      "weather":[  
         {  
            "astronomy":[  ],
            "date":"2015-12-11",
            "hourly":[  
               {  },
               {  },
               {  },
               {  },
               {  },
               {  },
               {  },
               {  }
            ],
            "maxtempC":"8",
            "maxtempF":"46",
            "mintempC":"4",
            "mintempF":"38",
            "uvIndex":"0"
         }
      ]
   }
}

由于空间原因,每小时对象被最小化。

我的问题是,当我通过 Retrofit 2.0 在我的应用程序中使用此 api 调用时,current_condition 大小为 0。请查看我的调试器的屏幕截图:

我的对象是正确的,基于浏览器的返回,我使用了http://www.jsonschema2pojo.org/ 以获得正确的结构和对象。我的改造代码如下:

public interface OpenWeatherApiInterface {

    @GET("?&format=json&num_of_days=5&key=API_KEY&")
    Call<OpenWeather> getWeatherForLocation(@Query("q") String city);
}

public class RestClient {

    private static OpenWeatherApiInterface mOpenWeatherApiInterface;
    private static String mBaseUrl = "http://api.worldweatheronline.com/free/v2/weather.ashx";


    public static OpenWeatherApiInterface getClient(){

        if(mOpenWeatherApiInterface==null){

            Retrofit client = new Retrofit.Builder()
                    .baseUrl(mBaseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

            mOpenWeatherApiInterface = client.create(OpenWeatherApiInterface.class);
        }
        return mOpenWeatherApiInterface;
    }
}

然后在我的主要活动中只是为了测试这一点,我将其称为如下:

 Call<OpenWeather> call = RestClient.getClient().getWeatherForLocation("London");
    call.enqueue(new Callback<OpenWeather>() {
        @Override
        public void onResponse(Response<OpenWeather> response, Retrofit retrofit) {
            Log.i("Main Activity", response.body().toString());

            if (response.isSuccess()) {
                OpenWeather weather = response.body();
                Data data = weather.getData();
                List<CurrentCondition> conditionList = data.getCurrentCondition();
                Log.i("MainA", "blah");

            } else {
                try {
                    Log.i("Main Activity", response.errorBody().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(Throwable t) {
            Log.i("Main Activity", "Failure");
        }
    });

我的班级开放天气

public class OpenWeather {

    private Data data;
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    /**
     *
     * @return
     * The data
     */
    public Data getData() {
        return data;
    }

    /**
     *
     * @param data
     * The data
     */
    public void setData(Data data) {
        this.data = data;
    }

    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }
}

还有我的班级数据:

public class Data {

    private List<CurrentCondition> currentCondition = new ArrayList<CurrentCondition>();
    private List<Request> request = new ArrayList<Request>();
    private List<Weather> weather = new ArrayList<Weather>();

    /**
     *
     * @return
     * The currentCondition
     */
    public List<CurrentCondition> getCurrentCondition() {
        return currentCondition;
    }

    /**
     *
     * @param currentCondition
     * The current_condition
     */
    public void setCurrentCondition(List<CurrentCondition> currentCondition) {
        this.currentCondition = currentCondition;
    }

    /**
     *
     * @return
     * The request
     */
    public List<Request> getRequest() {
        return request;
    }

    /**
     *
     * @param request
     * The request
     */
    public void setRequest(List<Request> request) {
        this.request = request;
    }

    /**
     *
     * @return
     * The weather
     */
    public List<Weather> getWeather() {
        return weather;
    }

    /**
     *
     * @param weather
     * The weather
     */
    public void setWeather(List<Weather> weather) {
        this.weather = weather;
    }
}

这是我第一次使用 Retrofit,我发现数组大小为 0 很奇怪。我想如果模型有问题我会崩溃

有人可以帮忙吗?

【问题讨论】:

  • 将此@SerializedName("current_condition") 添加到您的List&lt;CurrentCondition&gt; currentCondition 声明上方,并确保所有属性都与您的json 响应匹配。如果不是,它不能被改造解析,你会得到null属性。

标签: android json retrofit weather-api


【解决方案1】:

这是因为您有不同的 JSON 键和对象属性名称。 IE current_condition json 键应与 Data 类的键匹配,但您的字段名称为 currentCondition

如果你把它改成

public class Data {

private List<CurrentCondition> current_condition

我认为它会起作用

【讨论】:

  • 简单的错误...谢谢。我想这就是当你依赖 jsonschema2pojo.org 时会发生的事情
猜你喜欢
  • 2018-02-04
  • 2018-12-18
  • 1970-01-01
  • 1970-01-01
  • 2016-12-14
  • 2015-10-25
  • 2016-10-03
  • 2023-03-22
  • 2017-02-03
相关资源
最近更新 更多