我正在寻找最简单的方法或任何可用于在java中读取csv文件的jar并转换为嵌套的json。我尝试搜索各种来源,但所有的地方我都可以找到简单的json的结果,但我需要的是我应该读取csv文件,后来必须转换为以下格式的json字符串
{
"studentName": "Foo",
"Age": "12",
"address":{
"city" : "newyork",
"address1": "North avenue",
"zipcode" : "123213"
},
"subjects": [
{
"name": "English",
"marks": "40"
},
{
"name": "History",
"marks": "50"
}
]
}
我对csv中的任何格式都没问题,但是在读完csv文件后我需要像上面那样创建json字符串。
csv文件格式:
"studentName","Age","address__city","address__address1","address__zipcode","subjects__name","subjects__marks"
"Foo","12","newyork","North avenue","123213","English","40"
"","","","","","History","50"
答案 0 :(得分:1)
您可以使用SCIP Status : problem is solved [optimal solution found]
Solving Time (sec) : 0.01
Solving Nodes : 1
Primal Bound : +1.40200000000000e+03 (2 solutions)
Dual Bound : +1.40200000000000e+03
Gap : 0.00 %
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -0.0]
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -0.0]
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -0.0]
[-0.0, -0.0, -0.0, -0.0, 1.0, -0.0, -0.0, -0.0]
将JackSon
转换为CSV
。例如,请参阅以下代码:
JSON
如果您使用的是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