Play Framework:如何使用嵌套元素将原始字段序列化为 JSON
Play Framework: How to serialize raw fields to JSON with nested elements
我需要序列化一个 String
和一个 Option[Boolean]
:
val myWrites = (
(__ \ "box").write(
(
(__ \ "name").write[String] ~
(__ \ "default").writeNullable[Boolean]
).tupled
)
)
如果 Option[Boolean]
是 Some
那么我希望
{
"box": {
"name": "John",
"default": true
}
}
... 而如果 Option[Boolean]
是 None
我希望
{
"box": {
"name": "John"
}
}
给定以下变量...
val name = "John"
val default = Some(true)
...我如何将它们传递给 Writes
?我试过这个:
myWrites.writes(name, defaul)
...但无法编译:
No Json serializer found for type play.api.libs.functional.FunctionalBuilder[play.api.libs.json.OWrites]#CanBuild2[String,Option[Boolean]].
Try to implement an implicit Writes or Format for this type.
[error] (__ \ "box").write(
我认为这只是你写的一个错字。你有默认与默认
我能够使用
import play.api.libs.json._
import play.api.libs.functional.syntax._
val myWrites = (
(__ \ "box").write(
(
(__ \ "name").write[String] ~
(__ \ "default").writeNullable[Boolean]
).tupled
)
)
myWrites.writes("hi",Some(true))
我回来了
res0: play.api.libs.json.JsObject = {"box":{"name":"hi","default":true}}
我需要序列化一个 String
和一个 Option[Boolean]
:
val myWrites = (
(__ \ "box").write(
(
(__ \ "name").write[String] ~
(__ \ "default").writeNullable[Boolean]
).tupled
)
)
如果 Option[Boolean]
是 Some
那么我希望
{
"box": {
"name": "John",
"default": true
}
}
... 而如果 Option[Boolean]
是 None
我希望
{
"box": {
"name": "John"
}
}
给定以下变量...
val name = "John"
val default = Some(true)
...我如何将它们传递给 Writes
?我试过这个:
myWrites.writes(name, defaul)
...但无法编译:
No Json serializer found for type play.api.libs.functional.FunctionalBuilder[play.api.libs.json.OWrites]#CanBuild2[String,Option[Boolean]].
Try to implement an implicit Writes or Format for this type.
[error] (__ \ "box").write(
我认为这只是你写的一个错字。你有默认与默认
我能够使用
import play.api.libs.json._
import play.api.libs.functional.syntax._
val myWrites = (
(__ \ "box").write(
(
(__ \ "name").write[String] ~
(__ \ "default").writeNullable[Boolean]
).tupled
)
)
myWrites.writes("hi",Some(true))
我回来了
res0: play.api.libs.json.JsObject = {"box":{"name":"hi","default":true}}