JSON String to Case Class/Object
とを変換する汎用関数を作成しましたCase Class/Object to JSON String
。
build.sbt
ファイルに必要な SBT 依存関係:
name := "jackson-example"
scalaVersion := "2.12.11"
libraryDependencies += "com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.10.1"
libraryDependencies += "com.fasterxml.jackson.core" % "jackson-databind" % "2.10.1"
JSON 文字列からケース クラス/オブジェクトへ
def fromJson[T](json: String)(implicit m: Manifest[T]): Option[T] = {
Try {
lazy val mapper = new ObjectMapper() with ScalaObjectMapper
mapper.registerModule(DefaultScalaModule)
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
mapper.readValue[T](json)
} match {
case Success(x) => Some(x)
case Failure(err) => {
logger.error("@@@@Got " + err.getMessage() + " while JSON to Object:--> " + json)
None
}
}
}
ケース クラス/オブジェクトから JSON 文字列へ
def toJson[T](obj: T)(implicit m: Manifest[T]): Option[String] = {
Try {
lazy val mapper = new ObjectMapper() with ScalaObjectMapper
mapper.registerModule(DefaultScalaModule)
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
mapper.writeValueAsString(obj)
} match {
case Success(x) => Some(x)
case Failure (err) => {
logger.error("@@@@Got " + err.getMessage() + " while converting object to JSON:--> " + obj)
None
}
}
}