简体   繁体   中英

Troubles with gson.toJson(Collection)

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?

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.

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

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