简体   繁体   中英

Scala Jackson Serialization add computed field to serialized case class

I have a scala case class:

case class Person(name: String, age: Int) {
    def isMillenial: Boolean = age <= someConstantMillenialThreshold
}

This serializes into the following json (using the ScalaJsonFactory object mapper to serialize):

{
    name: "foo",
    age: 42
}

However I want it to be serialized as follows:

{
    name: "foo",
    age: 42,
    isMillenial: true
}

Is there any way of doing this in a simple way, preferably by using some Jackson annotation or something similar? Basically looking for any solution which doesn't involve changing the case class Person or creating new objects

Done! Looks like we can do this:

import com.fasterxml.jackson.annotation.JsonProperty
case class Person(name: String, age: Int) {
    @JsonProperty("isMillenial") def isMillenial: Boolean = age <= someConstantMillenialThreshold
}

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