类型为的json的scala读/写格式

类型为的json的scala读/写格式,json,scala,playframework-2.1,Json,Scala,Playframework 2.1,我在理解如何序列化类型时遇到问题 假设我习惯于以这种方式序列化: 类别: 在我的格式化程序中,我执行以下操作: trait ProductFormats extends ErrorFormats { implicit val localizedItemFormat = new Format[LocalizedItem]{ def writes(item: LocalizedItem):JsValue = { Json.obj( "itemId" -> item.ite

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

假设我习惯于以这种方式序列化:
类别:

在我的格式化程序中,我执行以下操作:

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相同的方式实现写入/读取)

e、 g:

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  

大致如下:

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类型的值。如果没有,则可以删除类型约束

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())
  ) 
 }
}