简体   繁体   中英

Excel to Json Conversion In Java

I have a problem where I would like to convert the below Excel data into a JSON format containing children. Here is the information about what I am talking about.

Given excel data

This data needs to be converted to the below format but unfortunately, I am unable to do so!

Type of JSON data needed

Here is the updated code snippet I am using to get the data.

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 
}

Please take a look and suggest your view or a sample code snippet to generate the data in the specified JSON format.

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 + "]";
    }


}

Runner code that uses 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));
    }

Output:

[ {
  "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" : [ ]
} ]

As you can see, the output is similar to your Type of JSON data needed .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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