我对 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 被创建,但只使用最新的对象,一遍又一遍。我究竟做错了什么?