Excel中的Excel到Json转换

时间:2018-03-20 13:40:07

标签: java json

我有一个问题,我想将下面的Excel数据转换为包含子项的JSON格式。以下是我正在谈论的内容的信息。

Given excel data

此数据需要转换为以下格式,但不幸的是,我无法这样做!

Type of JSON data needed

以下是我用来获取数据的更新代码段。

public static void excel2Csv(String file_path) {

    // Variables!
    Books b1, b2 = null;
    String jsonInString = "";
    int active_sheet_index = 0;

    // Initializing the parent and the children list!
    List<Books> bList = new ArrayList<Books>();
    List<Books> children = null;

    // Initializing the excel variables!        
    Sheet sheet = null;     
    Workbook workbook = null;
    FileInputStream inp = null;

    // Initializing the JSON Mapper variables!
    ObjectMapper mapper = null;

    try {
        // Reading the excel input for conversion!
        inp = new FileInputStream(new File(file_path));

        // Creating the excel workbook object!
        workbook = WorkbookFactory.create(inp);     

        // Get the first sheet!
        sheet = workbook.getSheetAt(active_sheet_index);
        Iterator<Row> iterator = sheet.iterator();
        while (iterator.hasNext()) {
            b1 = new Books();
            children = new ArrayList<Books>();

            // Iterating through the excel rows!
            Row row = iterator.next();

            // If Cell0 of the active row is blank or null!
            if(row.getCell(0)==null || row.getCell(0).getCellType()==Cell.CELL_TYPE_BLANK) {
                b2 = new Books();               
                b2.setBauthor(getCellValueAsString(row.getCell(1)));
                b2.setBcost(getCellValueAsString(row.getCell(2)));
                children.add(b2);
            } else {
                b1.setBname(getCellValueAsString(row.getCell(0)));
                b1.setBauthor(getCellValueAsString(row.getCell(1)));
                b1.setBcost(getCellValueAsString(row.getCell(2)));              
            }

            if (children!=null && children.size()>0) {
                b1.setChildren(children);
            }
            bList.add(b1);
        }

        mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.INDENT_OUTPUT, true);

        jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bList);
        System.out.println("Final Json= \n" + jsonInString);

        // Convert object to JSON string and save into file directly
        mapper.writeValue(new File("D:\\test.json"), new JSONTokener(jsonInString).nextValue().toString());
    } catch(Exception ex) {
        ex.printStackTrace();
    }
}

Pojo Class

public class Books {

    public String bname, bauthor, bcost;

    public List<Books> children;

    .... // Getters & setters 
}

请查看并建议您的观点或示例代码段,以便以指定的JSON格式生成数据。

1 个答案:

答案 0 :(得分:0)

import java.util.ArrayList;
import java.util.List;

public class Book {
    private final String name;
    private final String author;
    private final String cost;

    private final List<Book> children = new ArrayList<>();

    public Book(String name, String author, String cost) {
        this.name = name;
        this.author = author;
        this.cost = cost;
    }

    public void addToChildren(Book book) {
        children.add(book);
    }

    public String getName() {
        return name;
    }

    public String getAuthor() {
        return author;
    }

    public String getCost() {
        return cost;
    }

    public List<Book> getChildren() {
        return children;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((author == null) ? 0 : author.hashCode());
        result = prime * result + ((children == null) ? 0 : children.hashCode());
        result = prime * result + ((cost == null) ? 0 : cost.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Book other = (Book) obj;
        if (author == null) {
            if (other.author != null)
                return false;
        } else if (!author.equals(other.author))
            return false;
        if (children == null) {
            if (other.children != null)
                return false;
        } else if (!children.equals(other.children))
            return false;
        if (cost == null) {
            if (other.cost != null)
                return false;
        } else if (!cost.equals(other.cost))
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Book [name=" + name + ", author=" + author + ", cost=" + cost + ", children=" + children + "]";
    }


}

使用Book

的流道代码
    @Test
    public void batra() throws Exception {
        List<Book> books = new ArrayList<Book>();

        // this where you're logic in populating the books list goes.
        Book book1 = new Book("Software Craftmanship", "Pete McBreen", "26");
        Book book2 = new Book("Chad Fowler", "The Passionate Programmer", "16");
        Book book3 = new Book("Core Java", "O'Reilly", "11");

        Book book2Child1 = new Book("Software Craftmanship", "", "26");
        Book book2Child2 = new Book("Agile Development", "", "32");
        Book book2Child3 = new Book("Continuous Delivery", "", "41");

        book2.addToChildren(book2Child1);
        book2.addToChildren(book2Child2);
        book2.addToChildren(book2Child3);

        books.add(book1);
        books.add(book2);
        books.add(book3);

        ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
        System.out.print(mapper.writeValueAsString(books));
    }

输出:

[ {
  "name" : "Software Craftmanship",
  "author" : "Pete McBreen",
  "cost" : "26",
  "children" : [ ]
}, {
  "name" : "Chad Fowler",
  "author" : "The Passionate Programmer",
  "cost" : "16",
  "children" : [ {
    "name" : "Software Craftmanship",
    "author" : "",
    "cost" : "26",
    "children" : [ ]
  }, {
    "name" : "Agile Development",
    "author" : "",
    "cost" : "32",
    "children" : [ ]
  }, {
    "name" : "Continuous Delivery",
    "author" : "",
    "cost" : "41",
    "children" : [ ]
  } ]
}, {
  "name" : "Core Java",
  "author" : "O'Reilly",
  "cost" : "11",
  "children" : [ ]
} ]

如您所见,输出类似于所需的JSON数据类型