【问题标题】:How to read CSV and parse JSON using java code如何使用 Java 代码读取 CSV 并解析 JSON
【发布时间】: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


    【解决方案1】:

    我认为您看到的结果是正确的,这就是 JSON 应该的方式。 JSON 是一种基于键值的格式。


    您粘贴的输出只是意味着它是一个 json 对象数组
    [ { "Nutrient" : "Calories", "Amount" : " 289.00", "Unit" : " kcal" }, { "Nutrient" : "Fat", "Amount" : " 17.35", "Unit" : " g" } ]

    下面的 JSON 实际上没有意义,因为对象没有键。即使您尝试使用 Jackson 解析这种 JSON,它也会在线程“main”com.fasterxml.jackson.core.JsonParseException 中抛出错误 Exception: Unexpected character ('{' (code 123) ): 期望用双引号来开始字段名称 在 [Source: (String)"{ 。你可以试试这个


    { { "Nutrient" : "Calories", "Amount" : " 289.00", "Unit" : " kcal" }, { "Nutrient" : "Fat", "Amount" : " 17.35", "Unit" : " g" } }

    另一种选择是将每个 json 对象视为具有不同名称的唯一节点,如下所示,请参见关键字 set1 和 set2
    { "set1": { "Nutrient" : "Calories", "Amount" : " 289.00", "Unit" : " kcal" }, "set2": { "Nutrient" : "Fat", "Amount" : " 17.35", "Unit" : " g" } }


    出于某种原因,如果您真的想要 {} 而不是 [],那么只需进行字符串操作并将第一个“[”替换为“{”,将最后一个“]”替换为“}



    已编辑答案以匹配已编辑的问题: 现在我们知道您的 JSON 是 JSON 对象的数组,您必须将其读取为 JSONArray 而不是 JSONObject,您也不能再将其读取到 hashmap,它必须是一个列表,列表中的每个元素都将是包含您的数据的 JSONObject。工作代码sn-p如下

        String content = Files.readString(filePath);
        JSONArray jsonArray = new JSONArray(content);
        List<LinkedTreeMap> yourList = new Gson().fromJson(jsonArray.toString(), ArrayList.class);
    
        for(LinkedTreeMap l : yourList) {
            System.out.println(l.get("Amount"));
            System.out.println(l.get("Nutrient"));
            System.out.println(l.get("Unit"));
        }
    

    【讨论】:

    • 先生,但我在 HashMap 中需要它。您更新后的答案是在IndexRequest indexRequest = new IndexRequest(index, TYPE).source(yourList); 在线Exception in thread "main" java.lang.IllegalArgumentException: The number of object passed must be even but was [1] 上给我这个错误@
    • 1.需要完整的错误堆栈跟踪(这是一个工作代码,所以应该没有任何异常,你能确认你的 csv 是否有一个固定的模式?固定的列数?) 2. 你不能直接映射这种 JSON 数据对于任何哈希图,我们必须进行一些修改,请告诉我您希望如何将这些数据表示为哈希图?什么应该是键,什么应该是值?只有这样我们才能得出结论
    猜你喜欢
    • 1970-01-01
    • 2015-11-14
    • 2017-02-23
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    相关资源
    最近更新 更多