简体   繁体   中英

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

You are using the same Trip object in each loop. So, the same object is being referenced 3 times in arrayList. That is why the data is the same for all 3 objects. Please try below code :-

Trip.java

public class Trip {

    String origin;
    String destination;

    public String getOrigin() {
        return origin;
    }

    public void setOrigin(String origin) {
        this.origin = origin;
    }

    public String getDestination() {
        return destination;
    }

    public void setDestination(String destination) {
        this.destination = destination;
    }
}

In your activity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_demo);

    ArrayList<Trip> tripList = new ArrayList<Trip>();
    tripList = getTripList(json);

    Log.e("Trips", "" + tripList.size());

}

public ArrayList<Trip> getTripList(String json) {

    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++) {

            Trip trip = new Trip();
            trip.setOrigin(tripArray.getJSONObject(i).getString("origin"));
            trip.setDestination(tripArray.getJSONObject(i).getString("destination"));

            thisTripList.add(trip);
        }

        return (thisTripList);

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

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

Here you are creating thisTrip = new Trip(); for 1 time, and reusing it in for loop, so values are reflecting on object, and in the array you are storing it also has same object multiple times, so you are getting same value from array.

So create thisTrip = new Trip(); with in loop. that will solve your issue.

Example :

for(int i = 0; i < tripArray.length(); i++){
            JSONObject tripInstance = tripArray.getJSONObject(i);

            Trip thisTrip = new Trip();

            thisTrip.origin = tripInstance.getString("origin");
            thisTrip.destination = tripInstance.getString("destination");

            thisTripList.add(thisTrip);
        }

Try This simpler Code

class Trip {
     String origin;
     String destination;

 public Trip(String origin,String destination){
       this.origin = origin;
       this.destination = destination;
 }

  //getter and setter method here
 }

ArrayList<Trip> tripList;

public ArrayList<Trip> getTripList(String json){


    tripList = new ArrayList<>();

    try {
        JSONObject jsonObject = new JSONObject(json);
        JSONArray tripArray = jsonObject.getJSONArray("trips");

        for(int i = 0; i < tripArray.length(); i++){
            JSONObject tripInstance = tripArray.getJSONObject(i);
            tripList.add(new Trip(tripInstance.getString("origin"),tripInstance.getString("destination")));

        }

        return tripList;

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

In your oncreate method

ArrayList<Trip> tripList;
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tripList = getTripList(json);
}

The problem is that you are using the same Trip object each loop iteration. The same Trip object is being referenced 3 times in your list. That is why the origin and destination is the same for all 3 objects.

Try creating a new Trip object each loop iteration instead. This way, every object in the list is a different object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM