在我的示例中,如何告诉jackson objectmapper忽略某些类型(类)的字段 Object.class
,从序列化?
约束条件:
没有对源类的控制-它是第三方类
被序列化的类类型是未知的-我猜它取消了mixin的资格
此类字段名称预先未知
为了提供帮助,下面是一个单元测试字段 objectsList
以及 objectField
要从序列化中忽略它们,但其方法不正确,它是按名称而不是按类型过滤它们。
public static class FavoriteShows {
public Simpsons favorite = new Simpsons();
public BigBangTheory preferred = new BigBangTheory();
}
public static class Simpsons {
public String title = "The Simpsons";
public List<Object> objectsList = List.of("homer", "simpson");
public Object objectField = new HashMap() {{
put("mr", "burns");
put("ned", "flanders");
}};
}
public static class BigBangTheory {
public String title = "The Big Bang Theory";
public List<Object> objectsList = List.of("sheldon", "cooper");
public Object objectField = new HashMap() {{
put("leonard", "hofstadter");
put("Raj", "koothrappali");
}};
}
public abstract static class MyMixIn {
@JsonIgnore
private Object objectField;
@JsonIgnore
private Object objectsList;
}
@Test
public void test() throws JsonProcessingException {
// GIVEN
// Right solution must work for any (MixIn(s) is out of questions) Jackson annotated class
// without its modification.
final ObjectMapper mapper = new ObjectMapper()
.addMixIn(Simpsons.class, MyMixIn.class)
.addMixIn(BigBangTheory.class, MyMixIn.class);
// WHEN
String actual = mapper.writeValueAsString(new FavoriteShows());
System.out.println(actual);
// THEN
// Expected: {"favorite":{"title":"The Simpsons"},"preferred":{"title":"The Big Bang Theory"}}
assertThat(actual).isEqualTo("{\"favorite\":{\"title\":\"The Simpsons\"},\"preferred\":{\"title\":\"The Big Bang Theory\"}}");
}
2条答案
按热度按时间5hcedyr01#
其中一种方法是使用自定义
AnnotationIntrospector
.忽略类型为的所有字段
B
:c3frrgcw2#
如果您使用的是mixin,那么应该能够使用@jsonignoretype进行注解,使其忽略类。jackson中全局忽略类的引用文档