0

I am having problems understanding how to serialize a type.

Lets say I am used to serialize this way:
Class:

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

And in my Formatter I do:

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

My question is How do i use the same pattern for object that receive generic item/type (generic will have write/read implemented as the same way LocalizedItem has)

e.g:

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

When trying to implement in this way:

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

I Receive error:

class DTOResponse takes type parameters  

1 Answer 1

1

Something along the lines of:

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

Here the assumption is that you need to Format values of type T as well. If you do not, then you can remove the type constraint.

Not the answer you're looking for? Browse other questions tagged or ask your own question.