alpex
alpex

Reputation: 97

Circe trait fields not included in json

I have a simple trait which mixed in some case classes. When converting instances of that classes to JSON via circe, I realized that fields with default values in trait not included in JSON string.

I'm using io.circe.generic.auto._ for encoding

Example to illustarate it:

  trait Base {
    var timestamp: Timestamp = new Timestamp(System.currentTimeMillis())
    var version = 0
  }

  case class CC(id: String) extends Base

  val cc = CC("testId")
  val str = cc.asJson.noSpaces

which gives: {"id":"testId"}

So str does not contain timestamp and version values which I expect

I assume it uses encoder for case class and just skips a trait. What I need to do to include those fields too?

Tried this in different versions of circe (0.3.0 and 0.6.0)

Also can I decode that fields (which can have another values) from JSON string later, or should I better left this fields abstract and use default arguments in case classes?

Upvotes: 1

Views: 646

Answers (1)

longshorej
longshorej

Reputation: 381

You'd need to add those fields directly to the CC case class, or define your own encoder explicitly.

I'd do something like this:

  trait Base {
    def timestamp: Timestamp
    def version: Int
  }

  case class CC(id: String, timestamp: Timestamp, version: Int) 
    extends Base

  object CC {
    def apply(id: String) = new CC(
      id, new Timestamp(System.currentTimeMillis()), 0
    )
  }

  val cc = CC("testId")
  val str = cc.asJson.noSpaces

Upvotes: 1

Related Questions