I have the following play framework 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
)
So this:
{
line1: "My Street",
line2: "My Borough",
line3: "My Town",
line4: "My County"
}
Should transform to this:
{
address: {
line1: "My Street",
line2: "My Borough",
line3: "My Town",
line4: "My County"
}
}
My problem is that in the source json model, line4 is optional, so i only want to map it to address.line4 optionally as well. So:
{
line1: "My Street",
line2: "My Borough",
line3: "My Town"
}
Should also transform to this:
{
address: {
line1: "My Street",
line2: "My Borough",
line3: "My Town"
}
}
I have no idea how to do this with these transformers, and can find no similar problem after a lot of googling.
Thanks! Nic
Use Option
with 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 _)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.