0

I am trying to serialize / deserialize to json with json4s native the following case class :

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

case class FootballTeamId(value: String) extends Guid

trait Guid extends Id[String] with MappedTo[String]

object Guid {

  import scala.reflect.runtime._
  import scala.reflect.runtime.universe._

  def next[T <: Guid : TypeTag]: T = {
    val tt = typeTag[T]
    val constructor: MethodSymbol = tt.tpe.members.filter {
      m ⇒
        m.isMethod && m.asMethod.isConstructor
    }.head.asMethod
    currentMirror.reflectClass(tt.tpe.typeSymbol.asClass).reflectConstructor(constructor)(UUID.randomUUID().toString).asInstanceOf[T]
  }

}

I can do like this :

  case object UserIdSerializer extends CustomSerializer[UserId](format => ({
    case JString(s) => {
      UserId(s)
    }
  }, {
    case s: UserId => JString(s.value)
  }))

and have one custom serializer by type, but I'd rather be dry and have one custom serialiser that would do the job for all object of type Guid. I had no luck. I would be grateful for any help I could get on the topic !

Thanks

David Puleri
  • 144
  • 8
  • don't know about json4s, but if you are willing to have a look at Play-JSON, check http://pedrorijo.com/blog/scala-json/ and http://pedrorijo.com/blog/scala-json-part2/ – pedrorijo91 Apr 14 '16 at 18:05
  • I think `net.liftweb.mongodb.{JsonObjectMeta, JsonObject}` in lift-json would solve your problem, for more, you can check this [post](http://stackoverflow.com/questions/36097379/how-to-use-lift-jsons-class-extractor-constructor-mongo-bson-array/36114083#36114083). – Allen Chou Apr 15 '16 at 12:43

0 Answers0