No Json formatter for Option[String]?

孤街醉人 提交于 2019-11-30 09:57:38

Adding this code so that it is implicit-visible from your PersonFormat will make it work.

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.

You can use:

(__ \ "first_name").formatNullable[String]

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!