Reputation: 15
I want to fill my list always when my program goes through the for loop; however, the same data is written at all indices.
Integer nunAcc = JsonPath.read(obj, "$.['Account List'].length()");
JsonCharacter jChar = new JsonCharacter();
List<JsonCharacter> itemList = new ArrayList<>();
for(int i=0; i < nunAcc; i++) {
jChar.email = JsonPath.read(obj, "$.['Account List'][" + i + "].email");
jChar.password = JsonPath.read(obj, "$.['Account List'][" + i + "].password");
jChar.characterName = JsonPath.read(obj, "$.['Account List'][" + i + "].character");
itemList.add(jChar);
}
Upvotes: 1
Views: 40
Reputation: 140319
This:
JsonCharacter jChar = new JsonCharacter();
// ...
for(int i=0; i < nunAcc; i++) {
// Update jChar...
itemList.add(jChar);
}
is updating then adding the same instance to the list repeatedly.
Create a new instance of jChar
on each iteration:
for(int i=0; i < nunAcc; i++) {
JsonCharacter jChar = new JsonCharacter();
// Update jChar...
itemList.add(jChar);
}
Upvotes: 1