Reputation: 31
Okay, so lets say that the following is my JSON file. I can get the ID and name from the file just fine, but with the listings, it appears that it is only reading the finally listings into each person. So John and Dave both have the listings that Steve has. Do you know where I'm going wrong with this?
[
{
"id":1,
"name":"John",
"listings":[
{
"id":1,
"other_id":34,
},
{
"id":2,
"other_id":16,
},
{
"id":3,
"other_id":39,
}
]
},
{
"id":2,
"name":"Dave",
"listings":[
{
"id":1,
"other_id":156,
},
{
"id":2,
"other_id":189,
},
{
"id":3,
"other_id":312,
}
]
},
{
"id":3,
"name":"Steve",
"listings":[
{
"id":1,
"other_id":876,
},
{
"id":2,
"other_id":534,
},
{
"id":3,
"other_id":456,
}
]
}
]
And my java code
ArrayList<Person> people = new ArrayList<>();
JSONArray array = (JSONArray) parser.parse(reader);
for (Object object : array){
JSONObject jsonObject = (JSONObject) object;
int id = (int) jsonObject.get("id");
String name = (String) jsonObject.get("name");
ArrayList<Listing> listing = new ArrayList<>();
JSONArray listings = (JSONArray) jsonObject.get("listings");
for(Object item : listings){
JSONObject jsonItem = (JSONObject) item;
int itemID = (int) jsonItem.get("id");
int otherID = (int) jsonItem.get("other_id");
Listing temp = new Listing(itemID, otherID);
listing.add(temp);
}
people.add(new Person(id, name, listing));
}
for (Person person : people) {
System.out.println("ID: " + person.getId() + ", " + " Name: " + person.getName());
for (Listing list : person.getListing()) {
System.out.println("ID: " + list.getID() + ", " + " OtherID: " + list.getOtherID());
}
}
Upvotes: 1
Views: 89
Reputation: 372
more easy to use jackson parser.
ObjectMapper mapper;
mapper.readValue(jsonFile, new TypeReference<List<Person>>(){});
It will do all the work for you (populate the Person object)
Upvotes: 1
Reputation: 2052
The listing.add(id, otherID)
you are using is an ArrayList.add(int index,E element)
So I have changed a little bit check this working.
for (int index = 0; index < array.length(); index++) {
JSONObject jsonObject = (JSONObject) array.get(index);
int id = (int) jsonObject.get("id");
String name = (String) jsonObject.get("name");
List<Listing> listing = new ArrayList<>();
JSONArray listings = (JSONArray) jsonObject.get("listings");
for (int index1 = 0; index1 < listings.length(); index1++) {
JSONObject jsonItem = (JSONObject) listings.get(index1);
int itemID = (int) jsonItem.get("id");
int otherID = (int) jsonItem.get("other_id");
Listing listing2 = new Listing(itemID, otherID);
listing.add(listing2);
System.out.println(name + " " + itemID + " " + otherID);
}
people.add(new Person(id, name, listing));
}
Upvotes: 0