0

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";
}
oal
  • 411
  • 5
  • 15

1 Answers1

3

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.

Tair
  • 3,779
  • 2
  • 20
  • 33
  • This successfully prevents the fields being serialised which is interesting since the fields are not annotated with `@BeanProperty`, so no JavaBeans getter/setter methods are generated. However, annotating fields with `@JsonInclude` does not override the setting, so the fields cannot be included again on a case-by-case basis. This is therefore only a partial answer. – oal Mar 06 '17 at 10:41
  • @oloftus ah! I forgot about that part :) let me see what can be done in that regard.. – Tair Mar 06 '17 at 19:55
  • @oloftus the only way I found is to use `@JsonGetter` on a field – Tair Mar 06 '17 at 20:07