0

I have following case class

case class UserId(value: String) extends MappedTo[String]

(MappedTo is a generic id case class of slick.typesafe) and I declare its serializer in json4s

case object IdSerializer extends CustomSerializer[UserId](format => ( {
    case JString(s) => UserId(s)
    case JNull | JNothing => null
  }, {
    case i: UserId => JString(i.value)
    case JNull | JNothing => null
  }))

The problem is that I have more than 20 id fields like that, and I don't want to declare serializer for each of it. Is there a way to do it for MappedTo so it can be applied to all of its subclass?

mmdc
  • 1,677
  • 3
  • 20
  • 32

1 Answers1

0

Unless I'm misunderstanding something, you don't need to define your own serializer at all; case classes have a simple serialization method defined for them by the compiler, and Json4s will use that. If your other ID fields are members of a case class, they won't need one either.

Edit:

I gotcha. I'm reluctant to suggest this, since it is just patching over the real problem, which is the large number of case classes you are using, but something like this might work:

class IdSerializer[T] extends CustomSerializer[T <: MappedTo](format => ( {
    case JString(s) => new T(s)
    case JNull | JNothing => null
  }, {
    case i: T => JString(i.value)
    case JNull | JNothing => null
  }))

So for UserID, you would call IdSerializer[UserID]. A better solution is to stop using so many case classes, but maybe that isn't an option for you. Shrugs.

  • 1
    Yes json4s can serialize most of case classes. However, with `UserId(value:String)` its serialization is `{userId:{value:....}}` which is not what I expect. So I created a custom serialization to make it like `{userId:...}` – mmdc May 07 '16 at 23:20
  • Oh, I can see why you might want to do that. I'll update my answer. – David Prichard May 13 '16 at 17:20