我希望在使用Jackson时定义我的自定义序列化策略(包括哪些字段),我知道可以使用视图/过滤器来实现,但它引入了非常糟糕的问题-使用字段名称的字符串表示,这会自动启用自动重构问题。
如何强制Jackson仅序列化已注释的属性而不包括其他内容?
我希望在使用Jackson时定义我的自定义序列化策略(包括哪些字段),我知道可以使用视图/过滤器来实现,但它引入了非常糟糕的问题-使用字段名称的字符串表示,这会自动启用自动重构问题。
如何强制Jackson仅序列化已注释的属性而不包括其他内容?
如果禁用所有自动检测,它只会序列化您已经注释的属性--无论是属性本身还是getter。以下是一个简单的示例:
private ObjectMapper om;
@Before
public void setUp() throws Exception {
om = new ObjectMapper();
// disable auto detection
om.disable(MapperFeature.AUTO_DETECT_CREATORS,
MapperFeature.AUTO_DETECT_FIELDS,
MapperFeature.AUTO_DETECT_GETTERS,
MapperFeature.AUTO_DETECT_IS_GETTERS);
// if you want to prevent an exception when classes have no annotated properties
om.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}
@Test
public void test() throws Exception {
BlahClass blahClass = new BlahClass(5, "email", true);
String s = om.writeValueAsString(blahClass);
System.out.println(s);
}
public static class BlahClass {
@JsonProperty("id")
public Integer id;
@JsonProperty("email")
public String email;
public boolean isThing;
public BlahClass(Integer id, String email, boolean thing) {
this.id = id;
this.email = email;
isThing = thing;
}
}
如果您想在不为特定类型配置映射器的情况下执行此操作:
@JsonAutoDetect(
fieldVisibility = Visibility.NONE,
setterVisibility = Visibility.NONE,
getterVisibility = Visibility.NONE,
isGetterVisibility = Visibility.NONE,
creatorVisibility = Visibility.NONE
)
public class BlahClass {
@JsonProperty("id")
private Integer id;
@JsonProperty("email")
private String email;
}
@JsonIgnore
来避免序列化带注释的属性。 - Mena