1
考慮下面的代碼片段...播放:有條件的JSON創建
val selector = if (condition == true)
Json.obj("id" -> userId, "country" -> country)
else
Json.obj("id" -> userId)
...有沒有更好的–和更優雅的方式–做同樣的?
考慮下面的代碼片段...播放:有條件的JSON創建
val selector = if (condition == true)
Json.obj("id" -> userId, "country" -> country)
else
Json.obj("id" -> userId)
...有沒有更好的–和更優雅的方式–做同樣的?
OK,這裏是解決方案:
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
)
我希望它能幫助。
對於給出的例子,似乎「很好」,儘管對'== true'進行了愚蠢的明確檢查。 – user2864740
我只是想避免在ID部分重複... – j3d
鑑於您在Play中工作,JSON組合器和'writeNullable'會更好。 –