简体   繁体   中英

JSON4S does not serialize internal case class members

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?

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM