Victor Victor - 14 days ago 4
Java Question

Errors parsing json on Android (java)

I have a JSON object with the following format:

{
"_id": "1",
"trips": [{
"origin": "Spain",
"destination": "France"
}, {
"origin": "Italy",
"destination": "Germany"
}, {
"origin": "Portugal",
"destination": "Ireland"
}]
}


My goal is to parse this JSON and get an ArrayList of Trip, for which I have the following code:

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);
}
}


However, when I execute this method as shown below I get an ArrayList of size 3, which is correct, but which has all origin/destination values identical (i.e. Portugal,Portugal,Portugal; Ireland,Ireland,Ireland). What am I doing wrong?

@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);
//...

Answer

Try this.

public ArrayList<Trip> getTripList(String json){
    Trip thisTrip;
    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 = new Trip();
            thisTrip.origin = tripInstance.getString("origin");
            thisTrip.destination = tripInstance.getString("destination");

            thisTripList.add(thisTrip);
        }

        return(thisTripList);

    } catch (JSONException e) {
        e.printStackTrace();
        return(null);
    }
}