如何指定jackson只使用字段 – 最好全球
默认的jackon行为似乎使用两个属性(getters和setter)和字段序列化和反序列化为json。
我想使用这些字段作为序列化configuration的规范来源,因此不希望jackson看到属性。
我可以在个人课程的基础上加注释:
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
但我不想把这个放在每一个class上
是否有可能在全球进行configuration? 像添加一些到物体映射?
你可以像这样configuration单个的ObjectMapper:
ObjectMapper mapper = new ObjectMapper(); mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker() .withFieldVisibility(JsonAutoDetect.Visibility.ANY) .withGetterVisibility(JsonAutoDetect.Visibility.NONE) .withSetterVisibility(JsonAutoDetect.Visibility.NONE) .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
如果你想要它在全局设置,我通常通过一个包装类访问configuration的映射器。
在jackson2.0和以后,你可以简单地使用:
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; ... ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE); mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
closures自动检测。
我花了很多时间:为什么不呢
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
没有
setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE); setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE); setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
不适用于我的布尔getter / setter。 解决scheme是simpe:
@JsonAutoDetect(isGetterVisibility = Visibility.NONE, ... setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE);
为jackson1.9.10我使用
ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(JsonMethod.ALL, Visibility.NONE); mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
自动取消。
这个怎么样:我用mixin
不符合的对象
@Entity @Getter @NoArgsConstructor public class Telemetry { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long pk; private String id; private String organizationId; private String baseType; private String name; private Double lat; private Double lon; private Instant updateTimestamp; }
混入:
@JsonAutoDetect(fieldVisibility = ANY, getterVisibility = NONE, setterVisibility = NONE) public static class TelemetryMixin {}
用法:
ObjectMapper om = objectMapper.addMixIn(Telemetry.class, TelemetryMixin.class); Telemetry[] telemetries = om.readValue(someJson, Telemetry[].class);
没有什么说你不能对任何数量的类进行foreach并应用相同的mixin。
如果你不熟悉mixin,他们在概念上是简单的:mixin的结构是强加在目标类(根据jackson,而不是JVM而言)。