Home > Back-end >  CSV Jackson mapper numerical fields into String
CSV Jackson mapper numerical fields into String

Time:10-29

Is it possible wrap a numeric field from a pojo between quotes using CsvMapper from the jackson library?

public class Pojo{
    public String name;
    public int age;
}

Using CSVMapper jackson

Pojo pojo = new Pojo();
pojo.name= "Peter";
pojo.age= 22;
final CsvMapper csvMapper = new CsvMapper();
csvMapper.configure(CsvGenerator.Feature.ALWAYS_QUOTE_STRINGS, true);
final CsvSchema schema = csvMapper.schemaFor(Pojo.class).withoutHeader().withQuoteChar(CsvSchema.DEFAULT_QUOTE_CHAR);
final ObjectWriter ow = csvMapper.writer(schema);
 System.out.println(ow.writeValueAsString(pojo))  

My expected output will be "peter","4" but I'm getting "peter",4 :c

CodePudding user response:

Just add

@JsonFormat(shape=JsonFormat.Shape.STRING) 

to the int field of your pojo class :

public class Pojo{
    public String name;
    @JsonFormat(shape=JsonFormat.Shape.STRING) 
    public int age;
}

It can looks weird since it's a JSON annotation and not CSV, but it's close enough to works

  • Related