【发布时间】:2018-02-07 14:50:41
【问题描述】:
我一直在尝试通过 openweathermaps 从 API 获取 json 响应,但我似乎无法使其与 volley 或 Retrofit 一起使用,我将发布 volley 和 Retrofit 函数以及我在两者上遇到的错误以及json 消息本身
这是我试图捕获的 json 响应 http://samples.openweathermap.org/data/2.5/find?lat=55.5&lon=37.5&cnt=10&appid=b6907d289e10d714a6e88b30761fae22
这是 volley 代码“令人惊讶的是,我确实得到了我正在寻找的 json 的响应,但我在 on volley error msg 上得到了它”
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
// Initialize a new JsonArrayRequest instance
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.GET,
mJSONURLString,
null,
new Response.Listener<JSONArray>(){
@Override
public void onResponse(JSONArray response) {
textView.setText(response.toString());
try{
for(int i=0;i<response.length();i++){
}
}catch (Exception e){
e.printStackTrace();
}
}
},
new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error){
// this is where i get my json "how?"
System.out.println(error);
}
}
);
requestQueue.add(jsonArrayRequest);
这是一个完全不同的项目的改造代码“我正在测试两个 atm”
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
CitiesArrayAPI service = retrofit.create(CitiesArrayAPI.class);
Call<List<Cities>> call = service.loadCitiesFromAPI();
call.enqueue(new Callback<List<Cities>>() {
@Override
public void onResponse(Response<List<Cities>> response, Retrofit retrofit) {
System.out.println("test");
try {
List<Cities> cities = response.body();
for (int i = 0; i < cities.size(); i++) {
}
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
Log.d("onFailure", t.toString());
}
});
这是arrayapi的改造接口
public interface CitiesArrayAPI {
@GET("data/2.5/find?lat=55.5&lon=37.5&cnt=5&appid=b6907d289e10d714a6e88b30761fae22")
Call<List<Cities>> loadCitiesFromAPI();
}
这是我从改造中得到的错误,适用于 onFailure 方法
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
【问题讨论】:
-
看起来您没有以正确的格式投射该响应,因为您不仅获得了响应列表,因此您无法直接将该数据传递给列表。
-
那么我如何同时读取一个对象和一个数组呢?
-
如果我理解正确,那么你的意思是我没有单独获得列表 [],所以我应该找到一种方法来阅读整个内容,然后单独使用列表 [],对吗?
-
是的,你应该使用 jsonschema2pojo.org 来对 java 类进行响应
-
我不知道那是什么 tbh
标签: android json android-studio android-volley retrofit2