Converting an CSV file to a JSON object in Java

前端 未结 9 1677
太阳男子
太阳男子 2020-12-05 21:47

Is there an open source java library to convert a CSV (or XLS) file to a JSON object?

I tried using json.cdl, but somehow it does not seem to work for large CSV stri

9条回答
  •  [愿得一人]
    2020-12-05 22:46

    @Mouscellaneous basically answered this for you so please give him the credit.

    Here is what I came up with:

    package edu.apollogrp.csvtojson;
    
    import au.com.bytecode.opencsv.bean.CsvToBean;
    import au.com.bytecode.opencsv.bean.HeaderColumnNameMappingStrategy;
    import org.codehaus.jackson.map.ObjectMapper;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.List;
    
    public class ConvertCsvToJson {
        public static void main(String[] args) throws IOException, ClassNotFoundException {
            if (args.length > 1) {
                String pathToCsvFile = args[0];
                String javaBeanClassName = "edu.apollogrp.csvtojson.bean." + args[1];
                final File file = new File(pathToCsvFile);
                if (!file.exists()) {
                    System.out.println("The file you specified does not exist. path=" + pathToCsvFile);
                }
                Class type = null;
                try {
                    type = Class.forName(javaBeanClassName);
                } catch (ClassNotFoundException e) {
                    System.out.println("The java bean you specified does not exist. className=" + javaBeanClassName);
                }
    
                HeaderColumnNameMappingStrategy strat = new HeaderColumnNameMappingStrategy();
                strat.setType(type);
    
                CsvToBean csv = new CsvToBean();
                List list = csv.parse(strat, new InputStreamReader(new FileInputStream(file)));
                System.out.println(new ObjectMapper().writeValueAsString(list));
            } else {
                System.out.println("Please specify the path to the csv file.");
            }
        }
    }
    

    I used maven to include the dependencies, but you could also download them manually and include them in your classpath.

    
        net.sf.opencsv
        opencsv
        2.0
    
    
    
        org.codehaus.jackson
        jackson-mapper-asl
        1.9.12
    
    
        org.codehaus.jackson
        jackson-core-asl
        1.9.12
    
    

提交回复
热议问题