JSON4S does not serialize internal case class members

935 views Asked by At

I have a case class inheriting from a trait:

trait Thing {
  val name: String
  val created: DateTime = DateTime.now
}

case class Door(override val name: String) extends Thing

This is akka-http, and I'm trying to return JSON to a get request:

...
~
    path ("get" / Segment) { id =>
      get {

        onComplete(doorsManager ? ThingsManager.Get(id)) {
          case Success(d: Door) => {
            complete(200, d)
          }
          case Success(_) => {
            complete(404, s"door $id not found")
          }
          case Failure(reason) => complete(500, reason)
        }
      }
    } ~
...

but I only get the JSON of name. I do have the implicit Joda serializers in scope. if i override the 'created' timestamp in the constructor of the case class, it does get serialized, but it defines the purpose, as I don't need (or want) the user to provide the timestamp. I've tried moving the timestamp into Door (either as override or just by skipping the trait) and the result is the same (that is, no 'created').

how do I tell JSON4S to serialize internal members (and inherited ones) too?

1

There are 1 answers

2
λ Allquantor λ On BEST ANSWER

You have to define a custom format.

import org.json4s.{FieldSerializer, DefaultFormats}
import org.json4s.native.Serialization.write

case class Door(override val name: String) extends Thing
trait Thing {
  val name: String
  val created: DateTime = DateTime.now
}

implicit val formats = DefaultFormats + FieldSerializer[Door with Thing()]

val obj = new Door("dooor")
write(obj)