【发布时间】:2020-05-03 23:02:28
【问题描述】:
我正在使用以下代码读取 CSV 文件并将其数据解析为 JSON。
File inputFile = new File("in.csv");
File outputFile = new File("out.json");
CsvSchema csvSchema = CsvSchema.builder().setUseHeader(true).build();
CsvMapper csvMapper = new CsvMapper();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.writerWithDefaultPrettyPrinter().writeValue(outputFile,
csvMapper.readerFor(Map.class).with(csvSchema).readValues(inputFile).readAll());
这工作正常并给我如下输出,
[
{
"Nutrient" : "Calories",
"Amount" : " 289.00",
"Unit" : " kcal"
}, {
"Nutrient" : "Fat",
"Amount" : " 17.35",
"Unit" : " g"
}
]
但是需要的输出是
{
{
"Nutrient" : "Calories",
"Amount" : " 289.00",
"Unit" : " kcal"
}, {
"Nutrient" : "Fat",
"Amount" : " 17.35",
"Unit" : " g"
}
}
实际上,我需要读取从 CSV 转换而来的 JSON 文件。使用以下代码
String content = Files.readString(filePath);
JSONObject jsonObject1 = new JSONObject(content);
HashMap yourHashMap1 = new Gson().fromJson(jsonObject1.toString(), HashMap.class);
但是当我尝试这样做时,它给了我这个错误。
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
同时 json 文件应该以 { 而不是 [ 开头,同样它应该以 } 而不是 ] 结尾。
我的目标是消除这个错误。
【问题讨论】:
标签: json spring gson opencsv csvreader