Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson field based serialization

Tags:

java

json

jackson

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).

like image 863
jack_carver Avatar asked Apr 20 '12 04:04

jack_carver


2 Answers

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
}
like image 183
JohnC Avatar answered Oct 22 '22 21:10

JohnC


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.

like image 28
StaxMan Avatar answered Oct 22 '22 20:10

StaxMan