I am trying to marshall and un-marshall an Option[String] field to and from JSON. For my use-case, a None value should be marshaled as "null". Here is the code I have:
我正在尝试对JSON中的Option [String]字段进行编组和取消编组。对于我的用例,None值应该被封送为“null”。这是我的代码:
import org.scalatest.{FlatSpec, Matchers}
import play.api.libs.json._
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._
case class Person(
id: Int,
firstName: Option[String],
lastName: Option[String]
)
object Person {
implicit lazy val personFormat = (
(__ \ "id").format[Int] and
(__ \ "first_name").format[Option[String]] and
(__ \ "last_name").format[Option[String]]
)(Person.apply, unlift(Person.unapply))
}
class PersonSpec extends FlatSpec with Matchers {
"When Person instance is marshaled None fields " should
"be serialized as \"null\" values" in {
val person = Person(1, None, None)
import Person._
val json = Json.toJson(person)
println(json)
(json \ "id").as[Int] should be (1)
(json \ "first_name").get should be (JsNull)
(json \ "last_name").get should be (JsNull)
}
}
This results in the following compiler error:
这会导致以下编译器错误:
PersonSpec.scala:19: No Json formatter found for type Option[String]. Try to implement an implicit Format for this type.
[error] (__ \ "first_name").format[Option[String]] and
[error] ^
These are some of the things I have tried:
这些是我尝试过的一些事情:
Replacing (__ \ "first_name").format[Option[String]]
with (__ \ "first_name").formatNullable[String]
makes the compiler happy, but the test fails (""java.util.NoSuchElementException: None.get"") with the following output (from println(json)
)
用[__ \“first_name”)替换(__ \“first_name”)。format [Option [String]]。formatNullable [String]使编译器满意,但测试失败(“”java.util.NoSuchElementException:None.get “”)具有以下输出(来自println(json))
{"id":1}
This confirms with formatNullable
's behavior (don't render None valued fields).
这证实了formatNullable的行为(不渲染无值字段)。
Next, I replaced the format with a writes
. Like so:
接下来,我用写入替换了格式。像这样:
object Person {
implicit lazy val personWrite = (
(__ \ "id").write[Int] and
(__ \ "first_name").write[Option[String]] and
(__ \ "last_name").write[Option[String]]
)(unlift(Person.unapply))
}
Now, the compiler is happy and the test passes.
现在,编译器很高兴并且测试通过了。
But I now need to implement a separate Reads. If I could, I would rather not as it violates DRY principle.
但我现在需要实现单独的Reads。如果可以的话,我宁愿不要因为它违反DRY原则。
What am I doing wrong and when write[Option[...]] works perfectly why not format[Option[...]]?
我做错了什么,当写[Option [...]]完全有效时为什么不格式化[Option [...]]?
2 个解决方案
#1
9
Adding this code so that it is implicit-visible from your PersonFormat will make it work.
添加此代码以使其从PersonFormat隐式可见将使其工作。
implicit def optionFormat[T: Format]: Format[Option[T]] = new Format[Option[T]]{
override def reads(json: JsValue): JsResult[Option[T]] = json.validateOpt[T]
override def writes(o: Option[T]): JsValue = o match {
case Some(t) ⇒ implicitly[Writes[T]].writes(t)
case None ⇒ JsNull
}
}
I think that in play it is assumed that option-valued fields should be treated optional at all, hence the behaviour you observed with formatNullable.
我认为在游戏中假设选项值字段应该被视为可选的,因此您使用formatNullable观察到的行为。
#2
2
You can use:
您可以使用:
(__ \ "first_name").formatNullable[String]
(__ \“first_name”)。formatNullable [String]
#1
9
Adding this code so that it is implicit-visible from your PersonFormat will make it work.
添加此代码以使其从PersonFormat隐式可见将使其工作。
implicit def optionFormat[T: Format]: Format[Option[T]] = new Format[Option[T]]{
override def reads(json: JsValue): JsResult[Option[T]] = json.validateOpt[T]
override def writes(o: Option[T]): JsValue = o match {
case Some(t) ⇒ implicitly[Writes[T]].writes(t)
case None ⇒ JsNull
}
}
I think that in play it is assumed that option-valued fields should be treated optional at all, hence the behaviour you observed with formatNullable.
我认为在游戏中假设选项值字段应该被视为可选的,因此您使用formatNullable观察到的行为。
#2
2
You can use:
您可以使用:
(__ \ "first_name").formatNullable[String]
(__ \“first_name”)。formatNullable [String]