简体   繁体   English

与gson.toJson(集合)的麻烦

[英]Troubles with gson.toJson(Collection)

I have a problem with Gson to change a collection to a Json object. 我有一个问题,Gson将集合更改为Json对象。 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. 创建了JsonString,但只能使用最新的对象,一遍又一遍。 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. 您没有在循环中重新实现您的jsonItem,这意味着您正在向可变对象添加相同的引用。 The values are therefore always the ones of the last object of your collection. 因此,值始终是集合的最后一个对象的值。

Move JsonItem jsonItem = new JsonItem(); 移动JsonItem jsonItem = new JsonItem(); inside the while-loop. 在while循环中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM