我有以下格式的JSON對象:錯誤在Android(Java)的解析JSON
{
"_id": "1",
"trips": [{
"origin": "Spain",
"destination": "France"
}, {
"origin": "Italy",
"destination": "Germany"
}, {
"origin": "Portugal",
"destination": "Ireland"
}]
}
我的目標是分析這個JSON和獲得旅行的ArrayList,對此我有以下代碼:
class Trip {
String origin;
String destination;
}
ArrayList<Trip> tripList;
public ArrayList<Trip> getTripList(String json){
Trip thisTrip = new Trip();
ArrayList<Trip> thisTripList = new ArrayList<Trip>();
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray tripArray = jsonObject.getJSONArray("trips");
for(int i = 0; i < tripArray.length(); i++){
JSONObject tripInstance = tripArray.getJSONObject(i);
thisTrip.origin = tripInstance.getString("origin");
thisTrip.destination = tripInstance.getString("destination");
thisTripList.add(thisTrip);
}
return(thisTripList);
} catch (JSONException e) {
e.printStackTrace();
return(null);
}
}
然而,當我執行此方法如下所示,我得到尺寸爲3,這是正確的ArrayList,但是具有所有來源/目的地值相同(即葡萄牙,葡萄牙,葡萄牙;愛爾蘭,愛爾蘭,愛爾蘭)。我究竟做錯了什麼?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//...
Trip trip = new Trip();
tripList = new ArrayList<Trip>();
tripList = getTripList(json);
//...
提示未來。用getters和setter更好地使用模型類 –