我正在尝试从json获得响应,但出现空指针错误
这是我的改造界面
public interface RequestGeo {
@Headers("user-key: mykey")
@GET("geocode?lat=49.195061&lon=16.606836")
Call<JSONResponse> getJSON();
}
在我的MainActivity上,我得到了这段代码
private void loadJSON() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://developers.zomato.com/api/v2.1/")
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestGeo request = retrofit.create(RequestGeo.class);
Call<JSONResponse> call = request.getJSON();
call.enqueue(new Callback<JSONResponse>() {
@Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
geoCodeData = new ArrayList<>(Arrays.asList(jsonResponse.getGeocode()));
adapter = new RestaurantListAdapter(geoCodeData);
recyclerView.setAdapter(adapter);
}
@Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error", t.getMessage());
}
});
}
nullpointerexception错误在这里
geoCodeData = new ArrayList<>(Arrays.asList(jsonResponse.getGeocode()));
这是我的jsonResponse.java文件
public class JSONResponse {
private Geocode[] geocode;
public Geocode[] getGeocode(){
return geocode;
}
}
更新
Geocode.java类,在其中我完全按照要获取的json对象编写变量(有更多但我不想要它们)。
@Entity
public class Geocode {
@NonNull
@PrimaryKey private String title;
private String latitude;
private String longitude;
private String city_name;
public Geocode(String title, String latitude, String longitude, String city_name) {
this.title = title;
this.latitude = latitude;
this.longitude = longitude;
this.city_name = city_name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getCity_name() {
return city_name;
}
public void setCity_name(String city_name) {
this.city_name = city_name;
}
}