我有一个Scala案例课程
case class NumericParam(minValue: Option[Int] = None,
maxValue: Option[Int] = None,
decimalPlaces: Option[Int] = None,
signed: Option[Boolean] = None,
hintText: Option[String] = None)
和它的伴随对象,在这里我定义了一个隐式的
writes
方法object NumericParam {
implicit val writes = new Writes[NumericParam] {
override def writes(value: NumericParam): JsValue = {
Json.obj(
"dataType" -> "Numeric",
"minValue" -> value.maxValue,
"maxValue" -> value.maxValue,
"decimalPlaces" -> value.decimalPlaces,
"signed" -> value.signed,
"hintText" -> value.hintText
)
}
}
}
我正在添加字段
dataType
。有什么方法可以使用源自宏的Writes
值(来自Json.writes[NumericParam]
),而只需添加其他dataType
字段? 最佳答案
您可以使用Writes#transform
来完成。一种方法是使用功能JsValue => JsValue
。安全的方法:
implicit val writes = Json.writes[NumericParam] transform { js =>
js match {
case obj: JsObject => obj + ("dataType" -> JsString("Numeric"))
case _ => js
}
}
但是,我们确实知道
js
应该始终是JsObject
,因为我们在特定类型上进行操作,因此可以将其缩短。implicit val writes = Json.writes[NumericParam]
.transform(_.as[JsObject] + ("dataType" -> JsString("Numeric")))
例:
scala> val num = NumericParam(Some(1), Some(10), Some(2), Some(false), Some("test"))
num: NumericParam = NumericParam(Some(1),Some(10),Some(2),Some(false),Some(test))
scala> Json.toJson(num)
res5: play.api.libs.json.JsValue = {"minValue":1,"maxValue":10,"decimalPlaces":2,"signed":false,"hintText":"test","dataType":"Numeric"}
为了使上面的类型更安全且更通用,我们可以使用一些隐式魔术来扩展
OWrites
(始终写入JsObject
)。implicit class OWritesExt[A](owrites: OWrites[A]) {
/** Add a (key, value) pair to the JSON object,
* where the value is constant.
*/
def withConstant[B : Writes](key: String, value: B): OWrites[A] =
withValue(key, _ => value)
/** Add a key, value pair to the JSON object that is written, where
* the value depends on the original object.
*/
def withValue[B : Writes](key: String, value: A => B): OWrites[A] =
new OWrites[A] {
def writes(a: A): JsObject = owrites.writes(a) ++ Json.obj(key -> value(a))
}
}
用法:
implicit val writes = Json.writes[NumericParam]
.withValue("type", _.getClass.toString)
.withConstant("other", "something")
scala> Json.toJson(NumericParam(Some(1)))
res6: play.api.libs.json.JsValue = {"minValue":1,"type":"class NumericParam","other":"something"}
现在,您可以废弃一些原始的样板,并将这样的链接链接在一起。现在我只是想知道为什么我一直都没有这样做。