简体   繁体   中英

Jackson field based serialization

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

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
}

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM