From the activator console this works:
scala> import play.api.libs.json._
import play.api.libs.json._
scala> val testVal = Some("foo")
testVal: Some[String] = Some(foo)
scala> Json.obj("myJson" -> testVal)
res0: play.api.libs.json.JsObject = {"myJson":"foo"}
This also works:
scala> Json.obj("myJson" -> testVal.get)
res3: play.api.libs.json.JsObject = {"myJson":"foo"}
This fails:
scala> Json.obj("myJson" -> testVal.getOrElse(""))
<console>:12: error: type mismatch;
found : Object
required: play.api.libs.json.Json.JsValueWrapper
Json.obj("myJson" -> testVal.getOrElse(""))
But this works:
scala> val testVal2 = testVal.getOrElse("")
testVal2: String = foo
scala> Json.obj("myJson" -> testVal2)
res2: play.api.libs.json.JsObject = {"myJson":"foo"}
Why does the compiler reject my third example? testVal.getOrElse("")
evaluates to a String so why does the compiler think it is Object
in the third example above?
You can also help a bit getOrElse
method to directly define its return type
Json.obj("myJson" -> testVal.getOrElse[String](""))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With