【问题标题】:Convert Json - Integers without quotes, Strings with quotes转换 Json - 不带引号的整数,带引号的字符串
【发布时间】:2019-08-09 09:03:36
【问题描述】:

我正在读取一个包含一些字符串和一些整数列的 CSV 文件,并将它们转换为 JSON。在这种转换中,所有字段和值似乎都有双引号。但是我希望整数值不要有双引号。

我正在使用 Jackson Fasterxml,这是我的代码 sn-p

    File input = new File("/Users/name/1.csv");
    File output = new File("/Users/name/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();
    mapper.configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS, true);


    // Write JSON formated data to output.json file
    mapper.writerWithDefaultPrettyPrinter().writeValue(output, readAll);

这是我的预期输出:输出,请注意 id 和 budget 上没有双引号

[ {
  "id" : 120,
  "name" : "Name 1",
  "type" : "type1",
  "budget" : 100
}, 
{
  "id" : 130,
  "name" : "Name 2",
  "type" : "type2",
  "budget" : 200
},
{
  "id" : 140,
  "name" : "Name 3",
  "type" : "type2",
  "budget" : 130
},
{
  "id" : 150,
  "name" : "Name 4",
  "type" : "type4",
  "budget" : 400
}
}]

但是所有字段和值在转换后都有引号

[ {
  "id" : "120",
  "name" : "Name 1",
  "type" : "type1",
  "budget" : "100"
}, 
{
  "id" : "130",
  "name" : "Name 2",
  "type" : "type2",
  "budget" : "200"
},
{
  "id" : "140",
  "name" : "Name 3",
  "type" : "type2",
  "budget" : "130"
},
{
  "id" : "150",
  "name" : "Name 4",
  "type" : "type4",
  "budget" : "400"
}
}]

【问题讨论】:

  • 查看解析CSV返回的List&lt;Object&gt;中的项目——你的数字是Strings吗?如果是这样,那就是你的问题。

标签: json


【解决方案1】:

不幸的是,现在无法读取CSV 并指定仅使用模式的类型。您可以使用private int budget; 创建POJO,转换将自动完成。对于其他解决方案,看看这个问题:jackson-dataformat-csv: Mapping number value without POJO 你可以在哪里看到:

【讨论】:

  • 谢谢!我会看看他们。
猜你喜欢
  • 2017-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-21
  • 2022-11-21
  • 2023-01-27
相关资源
最近更新 更多