Using 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
has no effect.
I wish for no fields to be serialised unless a field is annotated with com.fasterxml.jackson.annotation.JsonInclude
.
Scala
class ScalaClass {
val field = "someField"
}
Java
public class JavaClass {
public String field = "someField";
}
Instead, disable MapperFeature.AUTO_DETECT_GETTERS
and use @JsonGetter
on a field.
This works for me:
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"}
The Java analogy to your Scala class is more likely to be:
public class JavaClass {
public String getField() { return "someField"; }
}
UPDATE: Used @JsonGetter
to include the field in serialization.