我怎样才能使用Java将抓取的数据转换为JSON

我已经成功从Excel工作表中提取数据,现在我想将提取的数据转换成JSON格式。 具体格式。 我怎样才能做进一步的转换部分?

Excel表视图

JSON格式应该是:

{Machine:M / C1,Time:12:00 PM,Status:Working,},{Machine:M / C2,Time:12:00 PM,Status:Working},} ……}

我写的从Excel表格中获取数据的代码:

try { POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("F:\\software\\list.xls")); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(0); HSSFRow row; HSSFCell cell; int rows; // No of rows rows = sheet.getPhysicalNumberOfRows(); int cols = 0; // No of columns int tmp = 0; for(int i = 0; i < 10 || i < rows; i++) { row = sheet.getRow(i); if(row != null) { tmp = sheet.getRow(i).getPhysicalNumberOfCells(); if(tmp > cols) cols = tmp; } } for(int r = 0; r < rows; r++) { row = sheet.getRow(r); if(row != null) { for(int c = 0; c < cols; c++) { cell = row.getCell((short)c); if(cell != null) { // Your code here System.out.println(cell); } } } } } catch(Exception ioe) { ioe.printStackTrace(); } 

你可以使用Gson (如果你不需要高性能)或者Jackson (如果你关心性能的话)。

添加gson作为依赖到您的项目。 如果您使用Gradle,只需将此行添加到build.gradle dependecies部分即可:

 compile group: 'com.google.code.gson', name: 'gson', version: '2.8.1' 

或者查看其他的构build系统的例子

有了Gson,一切都很简单。 为你的对象声明一个类:

 public class MachineStatus { @SerializedName("Machine") String machine; @SerializedName("Time") String time; @SerializedName("Status") String status; } 

然后准备这样的对象的列表

  ArrayList<MachineStatus> statuses = new ArrayList<>(); for(int r = 0; r < rows; r++) { row = sheet.getRow(r); if(row != null) { for(int c = 0; c < cols; c++) { cell = row.getCell((short)c); if(cell != null) { // Your code here System.out.println(cell); MachineStatus status = new MachineStatus(); status.machine = cell.getMachine(); // change this part to use correct method that will fetch data from cell status.time = cell.getTime(); // same here status.status = cell.getStatus(); // same here statuses.add(status); } } } } Gson gson = new GsonBuilder() .setPrettyPrinting() // comment this out if you need to save bandwidth; .create(); // Prints Json array string System.out.println(gson.toJson(statuses)); 

更多关于gson和对象的集合 。

我build议你为JSON条目创build一个POJO类,例如:

 public class MachineData { private String machine; private String time; private String status; public MachineData(String m, String t, String s) { this.machine = m; this.time = t; this.status = s; } //+ getters, setters } 

然后根据您从Excel中提取的数据创buildMachineData对象。 把它们放在一个列表中,然后你可以使用Jackson或者GSON把列表转换成JSON。

 // create a list of MachineData objects: List<MachineData> list = new LinkedList<>(); // then when you go through Excel rows: String machine = ... // parse from Excel String time = ... // parse from Excel String status = ... // parse from Excel // build a MachineData object MachineData md = new MachineData(machine, time, status); // and add it to the list: list.add(md); // after you finished with the Excel part Gson gson = new Gson(); String json = gson.toJson(list); // here you have the JSON in a string