繁体   English   中英

与gson.toJson(集合)的麻烦

[英]Troubles with gson.toJson(Collection)

我有一个问题,Gson将集合更改为Json对象。 这是我的代码:

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

这是输出:

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"},...}

创建了JsonString,但只能使用最新的对象,一遍又一遍。 我究竟做错了什么?

您没有在循环中重新实现您的jsonItem,这意味着您正在向可变对象添加相同的引用。 因此,值始终是集合的最后一个对象的值。

移动JsonItem jsonItem = new JsonItem(); 在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