我无法理解,我可以用Json变压器吗?
import play.api.libs.json._
val r = ( __ \ "opt").readNullable[String]
val w = ( __ \ "someOpt").writeNullable[String]
val o1 = Json.obj("noopt" -> "some opt value")
val o2 = Json.obj("opt" -> "some opt value")
r.reads(o1).map(w.writes)
r.reads(o2).map(w.writes)
...
scala> res6: play.api.libs.json.JsResult[play.api.libs.json.JsObject] = JsSuccess({},)
scala> res7: play.api.libs.json.JsResult[play.api.libs.json.JsObject] = JsSuccess({"someOpt":"some opt value"},/opt)
答案 0 :(得分:0)
源代码分析导致决定
val t = Reads.nullable[String]( __ \ "opt").map{
case Some(o) => JsPath.createObj( (__ \ "someOpt") -> JsString(o))
case _ => Json.obj()
}
或更熟悉(来自Json组合者)
val t = ( __ \ "opt").readNullable[String].map{
case Some(o) => Json.obj("someOpt" -> o)
case _ => Json.obj()
}
结果:
val o1 = Json.obj("noopt" -> "some opt value")
val o2 = Json.obj("opt" -> "some opt value")
o1.transform(t)
o2.transform(t)
scala> res23: play.api.libs.json.JsResult[play.api.libs.json.JsObject] = JsSuccess({},)
scala> res24: play.api.libs.json.JsResult[play.api.libs.json.JsObject] = JsSuccess({"someOpt":"some opt value"},/opt)