如果`Json.obj`包含`None`值,如何生成json字符串?

时间:2014-04-15 06:46:22

标签: json scala playframework option implicit

在游戏框架中:

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
           ^

如何解决?

1 个答案:

答案 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}

如果您的NoneOption,而不仅仅是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}