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 5 years have passed since last update.

【KMapper】プロパティ名のケースを変換してマッピングを行う【Kotlin】

Last updated at Posted at 2020-03-07

自作のKotlin Object to Kotlin Objectマッパー、KMapperの機能紹介です。

バージョンはKMapper 0.11で書いています。

プロパティ名を変換してマッピングを行う

「ソースがスネークケースで、マップ先がキャメルケース」というような場合、KMapperでは第二引数に変換関数を渡すことで、以下のように書くことができます。
この例では、変換関数としてGuavacom.google.common.base.CaseFormatを利用しています。

class CamelCaseDst(val camelCase: String)

fun test() {
    val expected = "camelCase"
    val src = mapOf("camel_case" to expected)

    val mapper = KMapper(CamelCaseDst::class) {
        CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, it)
    }
    val result = mapper.map(src)

    assertEquals(expected, result.camelCase)
}

変換に関する実装方針

この記法変換に関しては、変換回数を最小にするため、マップ先のプロパティを変換する方針で記述しました。
そのため、変換を記述したインスタンスでは、その変換先と合致する記法のソースを用いなければマッピングを行えません。

補足

KMapperでは記法の変換関数を提供しておりません。
GuavaJacksonなど、プロジェクトの基盤となるライブラリではこういった変換関数が提供されているので、そちらの利用をお願いします。

手前味噌ですが、Jacksonを使う場合は以下の記事にまとめてあります。

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?