1

我有以下播放框架 2.3 json 转换器

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"
    }
}

我不知道如何使用这些变压器来做到这一点,并且经过大量谷歌搜索后找不到类似的问题。

谢谢!网卡

4

1 回答 1

-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 _)
}
于 2015-08-03T14:26:37.280 回答