在游戏框架中:
import play.api.libs.json._
val obj = Json.obj(
"aaa" -> 111,
"bbb" -> Some(222)
)
println(obj.toString)
哪个输出:
{"aaa":111,"bbb":222}
但是,如果我将代码更改为:
val obj = Json.obj(
"aaa" -> 111,
"bbb" -> None
)
无法编译,并报告:
Error:(6, 17) diverging implicit expansion for type play.api.libs.json.Writes[None.type]
starting with method OptionWrites in trait DefaultWrites
"bbb" -> None
^
如何解决?
答案 0 :(得分:0)
Json.obj
可以正常使用None
,如果它是您所说的对象字段:
case class A(aaa: Int, bbb: Option[Int])
defined class A
val a = A(1, None)
a: A = A(1,None)
Json.obj("aaa" -> a.aaa, "bbb" -> a.bbb)
res1: play.api.libs.json.JsObject = {"aaa":1,"bbb":null}
如果您的None
是Option
,而不仅仅是None.type
正如编译器所说的那样,您也可以使您的示例正常工作:
Json.obj("aaa" -> 111, "bbb" -> None.asInstanceOf[Option[Int]])
res3: play.api.libs.json.JsObject = {"aaa":111,"bbb":null}
Json.obj("aaa" -> 111, "bbb" -> Option[String](null))
res4: play.api.libs.json.JsObject = {"aaa":111,"bbb":null}