简体   繁体   English

在Java中使用Jackson将CSV转换为JSON,如何制作嵌套对象?

[英]CSV to JSON with Jackson in java, how to make nested objects?

I want to parse csv file like this 我想这样解析csv文件

`labelA;labelB;label1C;label2C;
 val1;val2;val3;val4;`

into a JSON file like this 变成这样的JSON文件

[{
    "labelA" : "val1",
    "labelB" : "val2",
    "labelC" : "{
       "labelC1: : "val3"
       "labelC2: : "val4"
  }
}]

I how do go about making a nested object? 我该如何制作嵌套对象? Preferably without making a pojo. 最好不要打pojo。 Here is the code I've got so far: 这是到目前为止我得到的代码:

File input = new File(inputfile);
CsvSchema csvSchema=CsvSchema.emptySchema().withHeader().withColumnSeparator(';');
ObjectMapper csvMapper = new CsvMapper();
List entries = csvMapper.readerFor(Map.class).with(csvSchema).readValues(input).readAll();
ObjectMapper Csv2JsonMapper = new ObjectMapper();
Csv2JsonMapper.enable(SerializationFeature.INDENT_OUTPUT);
String json = Csv2JsonMapper.writeValueAsString(entries);

Read the file line by line... 逐行读取文件...

1) First line is considered as header and handle it independently. 1)第一行被视为标题,并独立处理。

2) Once you start iterating on values (line 2 onwards), Split the line by the separator. 2)一旦开始迭代值(从第2行开始),请用分隔符分隔该行。

3) Store the first 2 values in JSONObject. 3)将前两个值存储在JSONObject中。 { header0: value0, header1: value1 }

4) Create a new JSONObject to store the rest of values, Iterate over the the remaining values and populate this object. 4)创建一个新的JSONObject来存储其余的值,遍历其余值并填充此对象。 { header2: value2, ... headerX: valueX }

5) Store it as third value of the original object. 5)将其存储为原始对象的第三值。 { header0: value0, header1: value1, customHeader: <value from step 4> }

Sample code -- 示例代码-

    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ";";
    boolean firstLine = true;
    List<String> headers = new ArrayList<>();
    JSONArray result = new JSONArray();
    try {

        br = new BufferedReader(new FileReader(<csvFilePath>));
        while ((line = br.readLine()) != null) {
            if (firstLine) {
                firstLine = false;
                String[] headersCSV = line.split(cvsSplitBy);

                for (String header : headersCSV) {
                    headers.add(header);
                }
            } else {
                String[] valuesCSV = line.split(cvsSplitBy);
                JSONObject valueObj = new JSONObject();

                // first 2 values are constant.
                valueObj.put(headers.get(0), valuesCSV[0]);
                valueObj.put(headers.get(1), valuesCSV[1]);

                JSONObject nestedObj = new JSONObject();
                for (int i = 2; i < valuesCSV.length; i++) {
                    nestedObj.put(headers.get(i), valuesCSV[i]);
                }

                valueObj.put("labelC", nestedObj);

                result.put(valueObj);
            }
        }

        // your output is in result Object. 


    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

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

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