Reputation: 5732
I have a problem with Gson to change a collection to a Json object. This is my code:
Collection<BomItem> items = bh.getAllItems();
Iterator<BomItem> itemIterator = items.iterator();
Collection<JsonItem> jsonItems = new Vector<JsonItem>();
JsonItem jsonItem = new JsonItem();
while(itemIterator.hasNext()) {
BomItem item = itemIterator.next();
jsonItem.setItemId(item.getItemId());
jsonItem.setName(item.getDescription());
jsonItems.add(jsonItem);
}
System.out.println("json size:" + jsonItems.size());
Gson gson = new Gson();
String json = gson.toJson(jsonItems);
System.out.println("Json: " + json);
This is the output:
09:36:13,846 INFO [STDOUT] json size:402
09:36:13,849 INFO [STDOUT] Json: [{"itemId":68073,"name":"Automatically inserted"},{"itemId":68073,"name":"Automatically inserted"},{"itemId":68073,"name":"Automatically inserted"},...}
The JsonString is created, but only with the latest object, over and over again. What am I doing wrong?
Upvotes: 0
Views: 776
Reputation: 4122
while(itemIterator.hasNext()) {
BomItem item = itemIterator.next();
//declare jsonitem inside the loop
JsonItem jsonItem = new JsonItem();
jsonItem.setItemId(item.getItemId());
jsonItem.setName(item.getDescription());
jsonItems.add(jsonItem);
}
Upvotes: 1
Reputation: 47608
You are no reinstantiating your jsonItem in the loop, meaning that you are adding over and over the same reference to a mutable object. The values are therefore always the ones of the last object of your collection.
Move JsonItem jsonItem = new JsonItem();
inside the while-loop.
Upvotes: 1