我的问题与此类似:Play framework: read Json containing null values
implicit val readObj: Reads[ApplyRequest] = (
(JsPath \ "a").read[String] and
(JsPath \ "b").readNullable[String] and
(JsPath \ "c").readNullable[String] and
(JsPath \ "d").readNullable[Int]
) (ApplyRequest.apply _)
除了将可能为null的值解析为Option [String]之外,我希望其中一个值为String,但如果值不存在,则允许被解析的值为字符串“null”或空。
即。
implicit val readObj: Reads[ApplyRequest] = (
(JsPath \ "a").read[String] and
(JsPath \ "b").read[String] and // this can be null, but should turn into string "null"
(JsPath \ "c").readNullable[String] and
(JsPath \ "d").readNullable[Int]
) (ApplyRequest.apply _)
这可能吗?这样做的干净方法是什么?
我们很遗憾地使用2.4版本,因此没有2.6
中的默认行为答案 0 :(得分:1)
是的,可以使用let myObject = {
objectFunc: function() {
this.thing = 10;
},
addFunc: function(x) {
let result = this.thing + x;
return result;
}
}
console.log(myObject.addFunc(20));
方法。
有:
readWithDefault
case class ApplyRequest(a: String, b: String, c: Option[String], d: Option[Int])
private val json =
"""
|{
| "a": "test1",
| "b": null,
| "c": null,
| "d": 1
|}
""".stripMargin
已定义:
Reads
解析的:
implicit val readObj: Reads[ApplyRequest] = (
(JsPath \ "a").read[String] and
(JsPath \ "b").readWithDefault[String]("null") and // default value here
(JsPath \ "c").readNullable[String] and
(JsPath \ "d").readNullable[Int]
) (ApplyRequest.apply _)