简体   繁体   English

如何使用java将获取的数据转换为JSON

[英]How can i convert fetched data to JSON using java

I have successfully fetched data from excel sheet and now i want to convert the fetched data into JSON format. 我已成功从excel表中获取数据,现在我想将获取的数据转换为JSON格式。 In specific format. 具体格式。 How can i do further conversion part ? 我该如何进一步转换部分?

Excel工作表视图

The JSON format should be: JSON格式应该是:

{ Machine: M/C1, Time: 12:00 PM, Status: Working,}, { Machine: M/C2, Time: 12:00PM, Status: Working}, } ......} {机器:M / C1,时间:12:00 PM,状态:工作,},{机器:M / C2,时间:12:00 PM,状态:工作},} ......}

Code which i have written to fetch data from excel sheet: 我为从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();
    }

I suggest you to create a POJO class for the JSON entries, eg: 我建议你为JSON条目创建一个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
}

Then create MachineData objects from the data you extracted from Excel. 然后从您从Excel中提取的数据创建MachineData对象。 Put them in a list, then you can use Jackson or GSON to convert the list into JSON. 将它们放在列表中,然后您可以使用JacksonGSON将列表转换为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

You can use Gson (if you don't need high performance) or Jackson (if you care about performance). 您可以使用Gson (如果您不需要高性能)或Jackson (如果您关心性能)。

Add gson as dependecy to your project. 将gson添加为项目的依赖项。 If you use Gradle just add this line to build.gradle dependecies section: 如果您使用Gradle,只需将此行添加到build.gradle dependecies部分:

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

Or check other build systems examples here 或者在这里查看其他构建系统示例

With Gson everything is quite simple. 有了Gson,一切都很简单。 Declare a class for your object: 为您的对象声明一个类:

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

Then prepare a list of such objects 然后准备这样的对象列表

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

More on gson and collections of objects . 更多关于gson和对象的集合

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM