向Scala案例类添加JSON字段
我有一个Scala案例课程向Scala案例类添加JSON字段,json,scala,playframework,Json,Scala,Playframework,我有一个Scala案例课程 case class NumericParam(minValue: Option[Int] = None, maxValue: Option[Int] = None, decimalPlaces: Option[Int] = None, signed: Option[Boolean] = None,
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
)
}
}
}
我正在添加字段数据类型
。有没有办法使用宏派生的Writes
值(来自Json.Writes[NumericParam]
),只需添加额外的数据类型
字段?您可以使用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 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"}
现在,您可以废弃一些原始样板文件,并将这样的调用链接在一起。现在我只是想知道为什么我一直没有这样做。这就是我一直在寻找的。我原以为这会涉及到变换,但不知道怎么做。谢谢
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"}