2015-10-14 32 views
0

我有一个阶情况下的类:Scala的杰克逊序列化计算字段添加到序列化的情况下类

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

此串行化成以下JSON(使用ScalaJsonFactory对象映射器序列化):

{ 
    name: "foo", 
    age: 42 
} 

不过,我希望它被序列化如下:

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

有什么办法做t他以一种简单的方式,最好通过使用一些杰克逊注释或类似的东西?基本上寻找任何解决方案,不涉及更改case class Person或创建新对象

回答

0

完成!看起来我们可以这样做:

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