Jackson 序列化对象为 CSV 文件
依赖
代码语言:javascript复制<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-csv -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-csv</artifactId>
<version>2.14.0-rc3</version>
</dependency>
序列化
代码语言:javascript复制val zhiPinFile = File("...")
val jobList = ArrayList<Job>()
val csvMapper : CsvMapper = CsvMapper()
// schemaFor(Job::class.java) 需要序列化的对象类
// withHeader() 输出到csv文件第一行,不加则没有
val csvSchema : CsvSchema = csvMapper.schemaFor(Job::class.java).withHeader()
csvMapper.writer(csvSchema).writeValues(zhiPinFile).write(jobList)
元素排序
添加注解,不加默认按照首字母排序
代码语言:javascript复制@JsonPropertyOrder("name","description")
data Job class(val name : String, val description : String){}
参考:
How to serialize object to CSV file? Jackson JsonMappingException: Unrecognized column 'C': known columns {"A","B"} jackson-data-format-csv 读取csv文件——高级配置及原理解析