单个属性案例类的JSON格式

时间:2018-04-04 15:50:43

标签: scala playframework play-json

鉴于

case class Location(lat: Double, long: Double)
case class Resident(location: Location)

Resident

编写JSON格式化程序的最简单方法是什么?

我正在尝试使用FunctionalBuilder

val residentFormats: Format[Resident] = (
(JsPath \ "location").format[Location]
) (Resident.apply, unlift(Resident.unapply))

但是将它与单个属性案例类一起使用变得不容易。我后来的尝试倾向于涉及比我认为必要的许多代码。

会赞赏一些指示

1 个答案:

答案 0 :(得分:3)

只需使用:

object Resident {
  implicit val format: OFormat[Resident] = Json.format[Resident]
}

或者您可以拆分定义:

object Resident {
  implicit val reads: Reads[Resident] = Json.reads[Resident]
  implicit val writes: OWrites[Resident] = Json.writes[Resident]
}

您可以自定义reads并自行编写:

object Resident {
  implicit val reads: Reads[Resident] = json => {
    (json \ "location").validate[Location].map(Resident(_))
  }
  implicit val writes: OWrites[Resident] = resident => Json.obj("localtion" -> resident.location)
}

注意:如果您需要将名称从 camelCase 转换为 underscore_keys ,您可以定义隐式JsonConfiguration

object Resident {
  implicit val jsonConfig = JsonConfiguration(SnakeCase)
  implicit val format: OFormat[Resident] = Json.format[Resident]
}