0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

kotlinでヘッダーなしのcsvをPOJOにマッピングしたい

Posted at

build.gradleに依存関係を追加(バージョンは必ず揃えてください)

build.gradle
dependenies{
  implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.15.1"
  implementation "com.fasterxml.jackson.dataformat:jackson-dataformat-csv:2.15.1"
}

クラスを定義します。
@JsonPropertyOrderを宣言しないと、csvの要素をアルファベット順の項目にマッピングしようとします。

Customer.kt
@JsonPropertyOrder("id", "name", "age")
data class Customer(
    val id: Int,
    val name: String,
    val age: Int,
)

Javaと異なり、registerKotlinModuleを行う必要があるので、注意。

hoge.kt
fun hoge(){
    val mapper = CsvMapper().registerKotlinModule()
    val csv = "1234,Taro,23\n2345,Jiro,35"
    val customers = mapper.readerFor(Customer::class.java)
        .with(CsvMapper().schemaFor(Customer::class.java))
        .readValues<Customer>(csv)
        .readAll()
    println(customers)
}

以上で、CSVをPOJOへマッピングできました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?