转换Json-不带引号的整数,带引号的字符串

时间:2019-03-18 22:09:34

标签: json

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

我正在使用Jackson Fasterxml,这是我的代码段

    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" : 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"
}
}]

1 个答案:

答案 0 :(得分:1)

很遗憾,目前无法读取CSV并指定仅用于模式的类型。您可以使用POJO创建private int budget;,转换将自动完成。对于其他解决方案,请查看以下问题:jackson-dataformat-csv: Mapping number value without POJO,在这里您可以看到:

相关问题