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.

Kotlin Date オブジェクトを GSON で UTC 基準でシリアライズ・デシリアライズする

Last updated at Posted at 2018-10-02

Stack Overflow の以下 Q&A にある Java 版の答えをもとに、現時点で推奨の TypeAdapter を利用して Kotlin に翻訳した記事です。

class GsonUtcDateAdapter: TypeAdapter<Date?>() {
  private val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")

  init {
    format.timeZone = TimeZone.getTimeZone("UTC")
  }

  override fun write(out: JsonWriter?, value: Date?) {
    val writer = out!!
    if (value == null) {
      writer.nullValue()
    } else {
      writer.value(format.format(value))
    }
  }

  override fun read(`in`: JsonReader?): Date? {
    val reader = `in`!!
    if (reader.peek() == JsonToken.NULL) {
      reader.nextNull()
      return null
    } else {
      try {
        return format.parse(reader.nextString())
      } catch (e: java.text.ParseException) {
        throw JsonParseException(e)
      }
    }
  }
}

...
val gson = GsonBuilder().registerTypeAdapter(Date::class.java, GsonUtcDateAdapter()).create()
val date = gson.fromJson("\"2018-10-01T09:48:37.546Z\"", Date::class.java) // deserialize
val json = gson.toJson(date) // serialize

素の Gson は Date オブジェクトをシリアライズ・デシリアライズするとき、ローカルタイムゾーンを強制すると先の Stack Overflow 記事に書かれています。自分でアダプターを書いて仕込む必要があるのですね。

The gson default serializer always defaults to your local timezone, and doesn't allow you to specify the timezone. See the following link.....

https://code.google.com/p/google-gson/issues/detail?id=281

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?