[英]How to add a second object into jsonArray
我正在尝试读取Excel批量数据并将其保存到数据库中。 在读取excel文件时,第一行数据被推送到json数组中,而在读取第二行时,则没有将数据插入json中。 请检查以下代码。
private JsonArray readBulkUsers(String file) throws IOException {
int count = 0;
FileInputStream fis = new FileInputStream(file);
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(fis);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
JsonArrayBuilder blist = Json.createArrayBuilder();
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
JsonObjectBuilder userjson = Json.createObjectBuilder();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
if(row.getRowNum()==0){
continue; //just skip the rows if row number is 0
}
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if(count == 0) {
userjson.add("email", cell.getStringCellValue());
} else if(count == 1) {
userjson.add("firstname", cell.getStringCellValue());
} else if(count == 2) {
userjson.add("lastname", cell.getStringCellValue());
} else if(count == 3) {
userjson.add("password", cell.getStringCellValue());
}
count ++;
}
blist.add(userjson.build());
}
fis.close();
return blist.build();
}
低于我得到的值:[{“电子邮件”:“ test@gmail.com”,“名字”:“测试”,“姓氏”:“ ppppp”,“密码”:“密码”},{}]
请帮助我完成此循环。
在while内创建一个新的JsonObjectBuilder
while(rowIterator.hasNext())
{
count=0;
Row row = rowIterator.next();
if(row.getRowNum()==0){
continue; //just skip the rows if row number is 0
}
JsonObjectBuilder userjson = Json.createObjectBuilder();
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if(count == 0) {
userjson.add("email", cell.getStringCellValue());
} else if(count == 1) {
userjson.add("firstname", cell.getStringCellValue());
} else if(count == 2) {
userjson.add("lastname", cell.getStringCellValue());
} else if(count == 3) {
userjson.add("password", cell.getStringCellValue());
}
count ++;
}
blist.add(userjson.build());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.