带有Type的json的scala读/写格式

时间:2014-03-10 09:03:13

标签: json scala playframework-2.1

我在理解如何序列化类型时遇到问题。

让我说我习惯这种方式序列化:
分类:

case class LocalizedItem(itemId:String, var value:String)
{
    def this(itemId:Option[String]) = this(itemId.getOrElse(null), "")
    def this(itemId:String) = this(itemId, "")
}

在我的格式化程序中,我做了:

trait ProductFormats extends ErrorFormats {

  implicit val localizedItemFormat = new Format[LocalizedItem]{
def writes(item: LocalizedItem):JsValue = {
  Json.obj(
      "itemId" -> item.itemId,
      "value" -> item.value
      )
}
def reads(json: JsValue): JsResult[LocalizedItem] = 
JsSuccess(new LocalizedItem(
    (json \ "itemId").as[String],
    (json \ "value").as[String]
    ))
    }

我的问题是如何对接收通用项/类型的对象使用相同的模式(泛型将以与LocalizedItem相同的方式实现写/读)

例如:

case class DTOResponse[T](d: T) {
  def isError = false
  def get() = d }

尝试以这种方式实施时:

implicit val dtoResponseFormat = new Format[DTOResponse] {
 def writes(item: DTORespons):JsValue = {
  Json.obj(
      "itemId" -> item.itemId,
      "value" -> item.value
      ) }

我收到错误:

class DTOResponse takes type parameters  

1 个答案:

答案 0 :(得分:1)

有些事情:

implicit def dtoResponseFormat[T: Format] = new Format[DTOResponse[T]] {
 val tFormatter: Format[T] = implicitly[Format[T]]
 def writes(item: DTOResponse):JsValue = {
  Json.obj(
    "itemId" -> tFormatter.writes(item.get())
  ) 
 }
}

这里假设你需要格式化类型T的值。如果不这样做,则可以删除类型约束。