我有以下播放框架2.3 json transformer
val transAddress = (
(__ \ 'address \ 'line1).json.copyFrom( (__ \ 'line1).json.pick ) and
(__ \ 'address \ 'line2).json.copyFrom( (__ \ 'line2).json.pick ) and
(__ \ 'address \ 'line3).json.copyFrom( (__ \ 'line3).json.pick ) and
(__ \ 'address \ 'line4).json.copyFrom( (__ \ 'line4).json.pick ) and
(__ \ 'address \ 'postcode).json.copyFrom( (__ \ 'postcode).json.pick ) reduce
)
所以这个:
{
line1: "My Street",
line2: "My Borough",
line3: "My Town",
line4: "My County"
}
应转变为:
{
address: {
line1: "My Street",
line2: "My Borough",
line3: "My Town",
line4: "My County"
}
}
我的问题是在源json模型中,line4是可选的,所以我只想将它映射到address.line4。所以:
{
line1: "My Street",
line2: "My Borough",
line3: "My Town"
}
还应转变为:
{
address: {
line1: "My Street",
line2: "My Borough",
line3: "My Town"
}
}
我不知道如何使用这些变换器完成此操作,并且在经过大量的Google搜索后无法找到类似的问题。
谢谢! NIC
答案 0 :(得分:-1)
将Option
与readNullable
import play.api.libs.functional.syntax._
import play.api.libs.json._
case class Address(line1: String, line2: String, line3: String, line4: Option[String])
object Address {
implicit val reads: Reads[Address] = (
(JsPath \ "line1").read[String] and
(JsPath \ "line2").read[String] and
(JsPath \ "line3").read[String] and
(JsPath \ "line4").readNullable[String]
)(Address.apply _)
}