简体   繁体   中英

CSV Jackson mapper numerical fields into String

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM