7

I think Jackson does method based serialization, is there any way I could make it field based?

Ex:

class Bean {
    Integer i;
    String s;

    public Integer getI() { return this.i; }
    public void setI(Integer i) { this.i = i; }
    public bool isSetI() { return this.i != null; }

    // same for s as well
}

The output JSON has "i" and "setI". Is there anyway I could override this to get only "i"? Also it would be great if there was a way to do this without adding any annotations to the class (they are auto generated).

Helder Pereira
  • 5,522
  • 2
  • 35
  • 52
jack_carver
  • 1,510
  • 2
  • 13
  • 28

4 Answers4

13

Check out the @JsonAutoDetect annotation. Example:

@JsonAutoDetect(fieldVisibility=Visibility.ANY, getterVisibility=Visibility.NONE, isGetterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE)
public class Bean {
    Integer i;
    String s;

    Integer getI() { return this.i; }
    void setI(Integer i) { this.i = i; }
    bool isSetI() return { this.i == null; }

    // same for s as well
}
JohnC
  • 698
  • 7
  • 12
6

Jackson can use fields as well, yes; but by default only public fields are discovered. But you can use @JsonProperty to mark non-public fields.

One thing to note is that if there is both a method (setX, getX) and field (x), method will have precedence. This is usually not a problem, but if it is, you need to explicitly then disable method(s) that is not to be used, by adding @JsonIgnore enxt to them.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
5

To accomplish this without annotations you can configure the ObjectMapper before serializing/deserializing in the following manner:

ObjectMapper om = new ObjectMapper();
om.setVisibilityChecker(om.getSerializationConfig().getDefaultVisibilityChecker().
            withGetterVisibility(JsonAutoDetect.Visibility.NONE).
            withSetterVisibility(JsonAutoDetect.Visibility.NONE));
Nilzor
  • 18,082
  • 22
  • 100
  • 167
3

The accepted answer didn't produce the expected result for me. What works for me without adding annotations is configuring the ObjectMapper in the following way:

ObjectMapper om = new ObjectMapper()
        .setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE)
        .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

This is the way that seems to make more sense to me, which uses the fields instead of getters\setters like standard Java serialization would do.

Helder Pereira
  • 5,522
  • 2
  • 35
  • 52