停止默认情况下序列化所有字段的 jackson-scala-module

Stop jackson-scala-module serializing all fields by default

使用DefaultObjectMapper from jackson-scala-module, in the following examples, field is serialised in the Scala version, but not in the Java version. Setting com.fasterxml.jackson.databind.MapperFeature.AUTO_DETECT_FIELDS无效。

我希望没有字段被序列化,除非字段被注释为 com.fasterxml.jackson.annotation.JsonInclude

Scala

class ScalaClass {
  val field = "someField"
}

Java

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

相反,禁用 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"}

Java 类比您的 Scala class 更可能是:

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

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