给出以下代码片段......
val selector = if (condition == true)
Json.obj("id" -> userId, "country" -> country)
else
Json.obj("id" -> userId)
......还有更好 - 更优雅的方式吗?
答案 0 :(得分:1)
好的,这是解决方案:
import play.api.libs.json._
import play.api.libs.functional.syntax._
val userWrites = (
(__ \ 'id).write[String] ~
(__ \ 'country).writeNullable[String]
).tupled
val json: JsValue = userWrites.writes(
"1234",
if (condition == true) Some("Germany") else None
)
我希望它有所帮助。