停止jackson-scala-module默认序列化所有字段

时间:2017-02-27 16:02:35

标签: json scala jackson jackson-modules jackson-module-scala

使用DefaultObjectMapper中的jackson-scala-module,在以下示例中,field 在Scala版本中序列化,但不在Java版本中。设置com.fasterxml.jackson.databind.MapperFeature.AUTO_DETECT_FIELDS无效。

我希望除非使用com.fasterxml.jackson.annotation.JsonInclude注释字段,否则不会序列化任何字段。

Scala的

class ScalaClass {
  val field = "someField"
}

爪哇

public class JavaClass {
  public String field = "someField";
}

1 个答案:

答案 0 :(得分:3)

相反,请停用MapperFeature.AUTO_DETECT_GETTERS并在字段上使用@JsonGetter

这对我有用:

import com.fasterxml.jackson.annotation.JsonGetter
import com.fasterxml.jackson.databind.{MapperFeature, ObjectMapper, SerializationFeature}
import com.fasterxml.jackson.module.scala.DefaultScalaModule

val mapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)

mapper.disable(MapperFeature.AUTO_DETECT_GETTERS)
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)

class ScalaClass {
  val field = "someField"
  @JsonGetter val includedField = "fieldValue"
}

mapper.writer().writeValueAsString(new ScalaClass) // => res: String = {"includedField":"fieldValue"}

Scala类的Java类比更可能是:

public class JavaClass {
    public String getField() { return "someField"; }
}

更新:使用@JsonGetter将字段包含在序列化中。