Aqua267
Aqua267

Reputation: 953

Convert Json - Integers without quotes, Strings with quotes

I'm reading a CSV file with some strings and some integer columns and converting them to JSON. While this conversion, all fields and values seem to have double quotes around them. However I want the integer values NOT to have double quotes.

I'm using Jackson Fasterxml and here's my code snippet

    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);

Here's my expected output: Output, please note id and budget do not have double quotes on them

[ {
  "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
}
}]

However all fields and values have quotes after conversion

[ {
  "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"
}
}]

Upvotes: 1

Views: 1940

Answers (1)

Michał Ziober
Michał Ziober

Reputation: 38665

Unfortunately right now it is not possible to read CSV and specify type for using schema only. You can create POJO with private int budget; and conversion will be done automatically. For other solutions take a look on this question: jackson-dataformat-csv: Mapping number value without POJO where you can see:

Upvotes: 1

Related Questions