解析csv数据并转换为嵌套的json java [英] Parse csv data and convert to nested json java
问题描述
我正在寻找最简单的方法或任何可用的jar来读取Java中的csv文件并将其转换为嵌套的json.我尝试搜索各种来源,但所有地方我都能找到简单json的结果,但是我需要阅读csv文件,该文件以后必须转换为以下格式的json字符串
I'm searching for simplest way or any jar available to read csv file in java and convert to into nested json. I tried searching for various sources, but all the places i could find results for simple json, but my need is i should read csv file which later has to be converted to json string in the below format
{
"studentName": "Foo",
"Age": "12",
"address":{
"city" : "newyork",
"address1": "North avenue",
"zipcode" : "123213"
},
"subjects": [
{
"name": "English",
"marks": "40"
},
{
"name": "History",
"marks": "50"
}
]
}
我可以使用csv中的任何格式,但是在读取csv文件后,我需要创建上述的json字符串.
I'm fine with any format in csv, however after reading csv file i need to create json string like above.
csv文件格式:
"studentName","Age","address__city","address__address1","address__zipcode","subjects__name","subjects__marks"
"Foo","12","newyork","North avenue","123213","English","40"
"","","","","","History","50"
推荐答案
您可以使用JackSon
将CSV
转换为JSON
.例如,请参见以下代码:
You can use JackSon
to convert CSV
to JSON
. For example see the following code:
import java.io.File;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
public class CSV2JSON {
public static void main(String[] args) throws Exception {
File input = new File("input.csv");
File output = new File("output.json");
CsvSchema csvSchema = CsvSchema.builder().setUseHeader(true).build();
CsvMapper csvMapper = new CsvMapper();
// Read data from CSV file
List<object> readAll = csvMapper.readerFor(Map.class).with(csvSchema).readValues(input).readAll();
ObjectMapper mapper = new ObjectMapper();
// Write JSON formated data to output.json file
mapper.writerWithDefaultPrettyPrinter().writeValue(output, readAll);
// Write JSON formated data to stdout
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(readAll));
}
}
如果使用的是maven
,则可以添加Jackson
依赖项,如下所示:
If you are using maven
you can add the Jackson
dependency as following:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.9</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-csv</artifactId>
<version>2.8.9</version>
</dependency>
这篇关于解析csv数据并转换为嵌套的json java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!