Scala / Play 2.4 JSON格式问题 [英] Scala / Play 2.4 JSON Format issue

查看:149
本文介绍了Scala / Play 2.4 JSON格式问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类(在那里简化了一下),它将使用ID字段扩展表示数据库级别的某些对象的JSON格式:

I have following class (simplified a bit there) that would extend the JSON-format for certain objects that represent the Database-level with the ID-field:

import play.api.libs.json._
import play.api.libs.functional.syntax._

class EntityFormat[T <: Entity](entityFormatter: Format[T]) extends Format[T] {
  val extendedFormat: Format[T] = (
      __.format[T](entityFormatter) ~
     (__ \ "id").format[Option[Long]]
  )(tupleToEntity, entityToTuple)

  private def tupleToEntity(e: T, id: Option[Long]) = {
    e.id = id
    e
  }

  private def entityToTuple(e: T) = (e, e.id)

  def writes(o: T): JsValue = extendedFormat.writes(o)

  def reads(json: JsValue): JsResult[T] = extendedFormat.reads(json)
}

abstract class Entity {
  var id: Option[Long] = None
}

使用Play 2.3,我可以写

With Play 2.3, I could then write

implicit val userFormat: Format[User] = new EntityFormat(Json.format[User])

然后将使用生成的JSON中的ID字段。但是,使用Play 2.4我遇到了以下编译时问题:

Which would then work with with the ID-field being in the generated JSON. However, with Play 2.4 I'm getting following compile-time issues:

No Json formatter found for type Option[Long]. Try to implement an implicit Format for this type. (__ \ "id").format[Option[Long]]
missing arguments for method tupleToEntity in class DomainEntityFormat; follow this method with `_' if you want to treat it as a partially applied function )(tupleToEntity, entityToTuple)
                                                                                                                                                              ^
missing arguments for method tupleToEntity in class DomainEntityFormat; follow this method with `_' if you want to treat it as a partially applied function )(tupleToEntity, entityToTuple)
                                                                                                                                                                             ^

如何使用Play 2.4进行扩展以使这种JSON格式有效?

How should you do the extending with Play 2.4 to make that kind of JSON Format work?

推荐答案

而不是:

(__ \ "id").format[Option[Long]]

尝试:

(__ \ "id").formatNullable[Long]

这篇关于Scala / Play 2.4 JSON格式问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆