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

【Scala】Play FrameworkでJoda-Timeを含むJSONをパース

Last updated at Posted at 2021-12-18

概要

Play Frameworkでは、JSONをパースするplay-jsonというライブラリが用意されています。基本的な使い方は、こちらのドキュメントをご参考ください。
今回はこのplay-jsonで、Scalaでよく使われるJoda-Timeの日付型を、パースしたい場合の対応メモです。

対応方法

Joda-Timeをパースするためには、別途play-json-jodaというライブラリを使用します。このライブラリを、パースのオブジェクトでインポートしてあげればOKです。

実装サンプル

以下がplay-jsonのcombinatorsで実装した、パースのサンプルです。
JodaTimeをパースするために、DefaultJodaDateTimeReadsJodaDateTimeWritesをimportしています。

import org.joda.time.DateTime
import play.api.libs.json.JodaReads.DefaultJodaDateTimeReads
import play.api.libs.json.JodaWrites.JodaDateTimeWrites
import play.api.libs.json._
import play.api.libs.functional.syntax._

object SampleData {

  implicit val sampleDataFormat = (
    (__ \ "_id").format[String] ~
      (__ \ "name").format[String] ~
      (__ \ "register_user_id").format[String] ~
      (__ \ "register_date").format[DateTime] // これがJodaTimeの日付型
    ) (SampleData.apply, unlift(SampleData.unapply))

}

case class SampleData(id: String = "",
                      name: String = "",
                      registerUserId: String = "",
                      registerDate: DateTime = DateTime.now())
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?