我需要连接 BasicDBList 中的所有 BasicDBObject 。每次循环运行时,我的 BasicDBObject 仅包含 ONE json 元素,退出时我的 BasicDBList 不包含任何内容。
为什么会出现这种情况?放置 dbLinha.clear() 以避免重复,但每次循环运行时都会评估代码 BasicDBList 包含重复!
public BasicDBList readMetadados(Planilha planilha) {
List<String> cabecalho = new ArrayList<>();
int linhaReferencia = 0;
BasicDBObject dbLinha = new BasicDBObject();
BasicDBList listLinha = new BasicDBList();
try {
InputStream planilhaFile = new FileInputStream(FileUtils.getFile(UPLOAD_PATH, planilha.getPath()));
Sheet linhaInicial = new XSSFWorkbook(planilhaFile).getSheetAt(0);
Iterator<Row> rowIterator = linhaInicial.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
try {
if (cell.getCellType() != 3) {
if (cell.getCellType() == 1) {
if ("Veículo".equals(cell.getStringCellValue())) {
linhaReferencia = cell.getRow().getRowNum();
cabecalho.add(cell.getStringCellValue());
while (cellIterator.hasNext()) {
cabecalho.add(cellIterator.next().getStringCellValue());
}
break;
}
}
if (linhaReferencia != 0) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_FORMULA:
dbLinha.append(cabecalho.get(cell.getColumnIndex()), cell.getCellFormula());
break;
case Cell.CELL_TYPE_BOOLEAN:
dbLinha.append(cabecalho.get(cell.getColumnIndex()), cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
dbLinha.append(cabecalho.get(cell.getColumnIndex()), cell.getNumericCellValue());
break;
default:
dbLinha.append(cabecalho.get(cell.getColumnIndex()), cell.getStringCellValue());
}
}
}
} catch (IllegalStateException e) {
Log.info(this, "Erro ao obter valor da linha [{}] e coluna [{}]", cell.getRow().getRowNum(), cell.getColumnIndex());
}
}
if (!dbLinha.isEmpty()) {
for(int i = 0; i < cabecalho.size(); i++){
if(!dbLinha.containsKey(cabecalho.get(i))){
dbLinha.append(cabecalho.get(i), " ");
}
}
listLinha.add(dbLinha);
dbLinha.clear();
}
}
} catch (FileNotFoundException e) {
Log.error(this, "Erro ao processar planilha: Planilha não encontrada.", e);
} catch (IOException e) {
Log.error(this, "Erro ao processar planilha.", e);
}
System.out.println(listLinha.toString());
return listLinha;
}
输出
[ { } , { } , { } , { } , { } , { }]
第一次运行BasicDBList的内容是正确的,第二次开始复制并替换为添加的前项。
第一次运行循环时BasicDBList的值(“if (!dbLinha.isEmpty())”)
第二次
最佳答案
您尝试通过使用 clear
并反复使用同一对象 (dbLinha
) 来保存对象。那是行不通的。
当您将对象添加到列表时,它会添加对该对象的引用,而不是将该对象的副本添加到列表中。所以基本上,您第一次添加的是对 dbLinha 对象的引用,现在列表中的第一项指向与设置的 dbLinha 相同的对象到。
然后调用dbLinha.clear()
。
这意味着存储在列表中的引用是相同的,现在将显示一个空对象。然后,您将另一行读入同一对象,将另一个引用添加到列表中,然后再次清除它。
您的列表中充满了对您正在重复使用的单个对象的引用。以下是正在发生的情况的演示:
如果你想保留你的对象,你必须使用new
,而不是clear
。您必须创建一个新对象来存储下一位数据,因为添加到列表不会创建副本,而只是创建引用。所以你基本上必须让你添加的引用指向旧对象,然后从一个新对象开始。
关于java - 为什么我无法连接 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29658869/