鉴于
case class Location(lat: Double, long: Double)
case class Resident(location: Location)
为Resident
我正在尝试使用FunctionalBuilder
即
val residentFormats: Format[Resident] = (
(JsPath \ "location").format[Location]
) (Resident.apply, unlift(Resident.unapply))
但是将它与单个属性案例类一起使用变得不容易。我后来的尝试倾向于涉及比我认为必要的许多代码。
会赞赏一些指示
答案 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]
}