Freewind
Freewind

Reputation: 198228

How to generate json string if the `Json.obj` contains a `None` value?

In playframework:

import play.api.libs.json._

val obj = Json.obj(
  "aaa" -> 111,
  "bbb" -> Some(222)
)

println(obj.toString)

Which outputs:

{"aaa":111,"bbb":222}

But if I change the code to:

val obj = Json.obj(
  "aaa" -> 111,
  "bbb" -> None
)

It can't be compiled, and reports:

Error:(6, 17) diverging implicit expansion for type play.api.libs.json.Writes[None.type]
starting with method OptionWrites in trait DefaultWrites
  "bbb" -> None
           ^

How to fix it?

Upvotes: 1

Views: 790

Answers (1)

serejja
serejja

Reputation: 23851

Json.obj works fine with None if it is a field of an object as you say:

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}

You can make your example work as well if your None is an Option, not just None.type as compiler says:

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}

Upvotes: 0

Related Questions