MoshiでLocalDateTime型を変換するときのカスタムアダプター

LocalDateTime型のプロパティがあるdata classをJsonに変換しようとしたところエラーがでた。

Platform class java.time.LocalDateTime requires explicit JsonAdapter to be registered

data classとJsonに変換している関数 Jsonに変換している関数はRepositoryに定義している。

data class Hoge {
  val id: Int,
  val hogehoge: String
  val time: LocalDateTime,
}

private fun convertJson(hoge: Hoge): String {
    val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
    val jsonAdapter = moshi.adapter(Hoge::class.java)
    return jsonAdapter.toJson(hoge)
}

結論

LocalDateTime型用のアダプターを実装し、Moshi.Builderに追加する。

Moshiに内蔵されているadapterはプリミティブ型やMapなどでLocalDateTImeは対応していない。

github.com

FromJsonアノテーション、ToJsonアノテーションを使用してCustom Adapterを作る。

// LocalDateTimeAdapter.kt
import com.squareup.moshi.ToJson
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

class LocalDateTimeAdapter {
    @FromJson
    fun fromJson(json: String): LocalDateTime {
        return LocalDateTime.parse(json, DateTimeFormatter.ISO_DATE_TIME)
    }
    
    @ToJson
    fun toJson(value: LocalDateTime): String {
        return value.format(DateTimeFormatter.ISO_DATE_TIME)
    }
}

このLocalDateTimeAdapterMoshi.Builder()に追加することでLocalDateTime型を変換できるようになる。

CustomAdapterはKotlinJsonAdapterFactory()より前に書く必要があるので注意。

private fun convertJson(hoge: Hoge): String {
    val moshi = Moshi.Builder()
        .add(LocalDateTimeBuilder())
        .add(KotlinJsonAdapterFactory())
        .build()
    val jsonAdapter = moshi.adapter(Hoge::class.java)
    return jsonAdapter.toJson(hoge)
}

M1 MacBook Airを買ったのでHomebrewとanyenvを入れる

新しくM1 MacBook Airを購入したのでHomeberwとanyenvを入れていきます。

まずはHomebrewをインストール

https://brew.sh/index_jabrew.sh

まずは以下コマンドをターミナルで打ちます。

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

パスワードを入力するとインストールが始まります。

Press RETURN to continue or any other key to abort

インストール中に上記文言が出るのでReturnしましょう。

おそらく今のままbrew -vなどHomebrewのコマンドを打ったとしても

下記のようにコマンドがありませんと出ます。

zsh: command not found: brew

bashzshbrewコマンドを実行できるようパスを通す必要があります。

bashzshどちらが使用されているかは下記コマンドで確認。

echo $SHELL

/bin/zsh

以下コマンドを実行して.zshrcがあるか確認します。

cd ~
ls -la

無ければ下記コマンドで作成しましょう。

touch .zshrc

下記コマンドでHomebrewのパスを通します。

echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> /Users/ユーザー名/.zshrc

追加した内容の反映コマンドも忘れずに。

$ source ~/.zshrc

これで下記コマンドを打てば動いていることを確認できます。

$ brew help

続いてanyenvのインストール

github.com

下記コマンドを実行すると

$ brew install anyenv

初期化処理を求められるので.zshrcに追加してシェルを再起動します。

$ echo 'eval "$(anyenv init -)"' >>  ~/.zshrc

$ exec $SHELL -l

最後に初期化しましょう

$ anyenv install --init
Do you want to checkout https://github.com/anyenv/anyenv-install.git? [y/N]:

と出るのでyを入力、エンター

Completed!と出ればOK