Matt
Matt

Reputation: 426

JSONArray weird results

I was trying to get some information from a different class in java using JSONArrays and JSONObjects but for some reason I get very weird results.

My Info.java class I have:

public JSONArray getSpawnedPets() {
    JSONArray petsArray = new JSONArray();
    JSONObject petO = new JSONObject();
    boolean spawned = false;
    for (int i = 0; i <= 3; i++) {
        spawned = true;
        if (spawned) {
            petO.put("petID", i);
            petO.put("petOwner", "owner"+i);
            petO.put("petName", "name");
            petO.put("color", "s");
            petO.put("particle", "s");
            petsArray.add(petO);
        }
    }
    return petsArray;
}

On my Main.java class I have:

public class main {
    public static void main(String[] args) {
        JSONArray petsArray = new JSONArray();
        Info in = new Info();
        petsArray = In.getSpawnedPets();
        if (petsArray != null) {
            for (int i = 0; i < petsArray.size(); i++) {
                JSONObject po = (JSONObject) petsArray.get(i);
                System.out.println("PetInfo:");
                System.out.println(po.get("petID")+":");
                System.out.println(""+po.get("petName"));
                System.out.println(""+po.get("petOwner"));
            }
        }
    }
}

The results were supposed to be increasing but yet I get this:

PetInfo:
3:
name
owner3
PetInfo:
3:
name
owner3
PetInfo:
3:
name
owner3
PetInfo:
3:
name
owner3

Did I do something wrong? I can't find my problem, the same code but not using classes works, but I have to use classes for it.

Cheers.

Upvotes: 1

Views: 39

Answers (1)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

Create jsonobject in every iteration otherwise , there is only one JSONObject JSONObject petO = new JSONObject(); which is being updated in every iteration of loop

 JSONArray petsArray = new JSONArray();
 JSONObject petO;
    //boolean spawned = false; // no need of it
    for (int i = 0; i <= 3; i++) {
        //spawned = true;
        //if (spawned) { // no need of it , has no effect, always true
            petO = new JSONObject();
            // ^^^^^^^^^^^^^^^^^
            petO.put("petID", i);
            petO.put("petOwner", "owner"+i);
            petO.put("petName", "name");
            petO.put("color", "s");
            petO.put("particle", "s");
            petsArray.add(petO);
        //}
    }

Note : Since spawned is a local variable and will be set to true in first iteration and has no effect in code so there is no need of if

Upvotes: 3

Related Questions