我正在使用firts時間在我的Android應用程序上進行翻新。 這是我必須以檢索JSON對象的結構:Android Retrofit json響應成谷歌地圖錯誤
{
"placemarks":[
{
"address":"Via di Santa Maria a Marignolle, 15, 50124 Firenze",
"coordinates":[
11.23348,
43.75855,
0
],
"engineType":"CE",
"exterior":"GOOD",
"fuel":100,
"interior":"GOOD",
"name":"049/EV284TP",
"smartPhoneRequired":false,
"vin":"WME4513341K774636"
}
]
}
我有寫這個POJO的模型對象「地標」,所有otehr項目。 我已經編寫代碼以檢索JSON數據,並把它放到地圖:
private void getPlacemark(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://www.car2go.com/api/v2.1/vehicles?loc=roma&oauth_consumer_key=roadzapp&format=json")
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService service = retrofit.create(APIService.class);
Call<ResponsePlacemarks> call = service.getPlacemark();
call.enqueue(new Callback<ResponsePlacemarks>() {
@Override
public void onResponse(Response<ResponsePlacemarks> response, Retrofit retrofit) {
Log.d("response: ", String.valueOf(response.body()));
try {
mMap.clear();
// This loop will go through all the results and add marker on each location.
for (int i = 0; i < response.body().getPlacemarks().size(); i++) {
Double lat = response.body().getPlacemarks().get(i).getCoordinates().get(1);
Double lng = response.body().getPlacemarks().get(i).getCoordinates().get(0);
String placeName = response.body().getPlacemarks().get(i).getAddress();
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(lat, lng);
// Position of Marker on Map
markerOptions.position(latLng);
// Adding Title to the Marker
markerOptions.title(placeName);
// Adding Marker to the Camera.
Marker m = mMap.addMarker(markerOptions);
// Adding colour to the marker
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
// move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
}
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
}
});
}
但現在,當我運行的應用程序的JSON是音符負荷和我有錯誤的for循環的第一行:
顯示java.lang.NullPointerException:嘗試上的空對象引用
您好有調用虛擬方法的java.util.List android.mobility.com.mobiity.model.ResponsePlacemarks.getPlacemarks()'發現錯誤。 在APIService上,我以這種方式設置@GET方法:@GET(「。」),因爲我使用URL作爲URL到BaseURL中。所以,如果我將所有網址設置爲@GET,該方法可以正常工作。 我如何只能使用BaseULRalso的URL到@GET中?
你應該在上面的評論中發佈這個。 –
@ cricket_007你是stackoverflow警察嗎?就我而言,我回答了問題的最可能原因。爲什麼你不使用評論,因爲你的回答的第二部分正是我所回答的(並且很可能是NPE的原因) –
考慮到你在答案中提出了一個問題,我會說這不會使一個很好的答案...另一方面,我的回答解決了OkHttp的另一個問題,只允許調用一次'response.body()'。 –