【问题标题】:How to add a second object into jsonArray如何将第二个对象添加到 jsonArray
【发布时间】:2015-05-03 20:33:32
【问题描述】:

我正在尝试读取 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();
}

低于我得到的价值: [{"email":"test@gmail.com","firstname":"test","lastname":"ppppp","password":"password"},{}]

请帮我完成这个循环。

【问题讨论】:

  • 您永远不会将count 重置为零,因此它永远不会在第一个字段之后向 JSON 列表添加更多字段。
  • 任何解决方案。

标签: java arrays json


【解决方案1】:

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

}

【讨论】:

    猜你喜欢
    • 2018-10-06
    • 1970-01-01
    • 2011-12-15
    • 2011-03-30
    • 2014-04-22
    • 2021-06-15
    • 1970-01-01
    • 2022-09-22
    • 1970-01-01
    相关资源
    最近更新 更多