在我的 Java 应用程序中使用 Jackson 进行序列化(POJO 到 JSON)和反序列化(JSON 到 POJO)时,我通常希望保留所有字段,因此使用(默认)JsonInclude.Value.ALWAYS
.
为了允许通过应用程序的 Rest API 进行部分更新,我还想区分设置为 null
的值。具体而言,该值保持不变。为此,Java8 Optional<?>
类似乎是正确的选择。
为了获得适当的支持,我必须添加 Jdk8Module
到ObjectMapper
。一切都非常简单。
开箱即用的反序列化行为正是我想要的。不存在的字段保留其默认值(此处: null
)和显式提供的 null
值被反序列化为 Optional.empty()
(或Optional.ofNullable(null)
)。
我想要的是 Optional<?>
显式值为 null
的字段从生成的 JSON 中排除,但始终包含任何其他字段(例如普通 Integer
)(即使它是 null
)。
众多可用选项之一是 MixIn
。不幸的是,一个MixIn
可能适用于其他注释,但不适用于 @JsonInclude
(这似乎是 jackson 的一个错误)。
public class OptionalObjectMappingTest {
public static class MyBean {
public Integer one;
public Optional<Integer> two;
public Optional<Integer> three;
public Optional<Integer> four;
}
@JsonInclude(JsonInclude.Include.NOT_NULL)
public static class OptionalMixIn {}
private ObjectMapper initObjectMapper() {
return new ObjectMapper()
.registerModule(new Jdk8Module())
.setSerialisationInclusion(JsonInclude.Include.ALWAYS)
.addMixIn(Optional.class, OptionalMixIn.class);
}
@Test
public void testDeserialisation() {
String json = "{\"one\":null,\"two\":2,\"three\":null}";
MyBean bean = initObjectMapper().readValue(json, MyBean.class);
Assert.assertNull(bean.one);
Assert.assertEquals(Optional.of(2), bean.two);
Assert.assertEquals(Optional.empty(), bean.three);
Assert.assertNull(bean.four);
}
@Test
public void testSerialisation() {
MyBean bean = new MyBean();
bean.one = null;
bean.two = Optional.of(2);
bean.three = Optional.empty();
bean.four = null;
String result = initObjectMapper().writeValueAsString(bean);
String expected = "{\"one\":null,\"two\":2,\"three\":null}";
// FAILS, due to result = "{one:null,two:2,three:null,four:null}"
Assert.assertEquals(expected, result);
}
}
<小时/>
有多种方法可以(动态)包含/排除字段及其值,但似乎没有一种“官方”方法可以解决问题:
-
@JsonInclude
每个Optional<?>
上的注释字段实际上做了我想做的事情,但这太容易忘记而且很麻烦。 - 自定义
MixIn
应该允许JsonInclude
的全局定义每个类型的注释,但显然没有应用(根据上面的示例测试)。 -
@JsonIgnore
(和相关的)注释是静态的,不关心字段的值。 -
@JsonFilter
需要在包含Optional
的每个类上进行设置字段,您需要了解PropertyFilter
中的每种受影响的类型。 IE。甚至比仅仅添加JsonInclude
更有值(value)每个Optional
领域。 -
@JsonView
不允许根据给定 bean 实例的字段值动态包含/排除字段。 - 自定义
JsonSerializer<?>
通过ObjectMapper.setNullValueSerializer()
注册仅在插入字段名称后调用,即如果我们不执行任何操作,生成的 JSON 将无效。 - 自定义
BeanSerializerModifier
在将字段名称插入 JSON 之前涉及,但它无法访问字段的值。
最佳答案
Edit:<小时/>As per StaxMan's answer, this doesn't seem to be a bug but a feature, as mix-ins are not meant to add annotations for every property of a certain type. The attempt of using mix-ins as described in the question just adds the
@JsonInclude
annotation on theOptional
class which has a different meaning (already described in that other answer).
从 jackson-databind 版本 2.9.0 开始的解决方案
由于 mix-ins 的设计行为不同,因此 ObjectMapper
的 configOverride()
上有一个新的配置选项:
setIncludeAsProperty()
配置就这么简单:
private ObjectMapper initObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper()
.registerModule(new Jdk8Module())
.setSerializationInclusion(JsonInclude.Include.ALWAYS);
objectMapper.configOverride(Optional.class)
.setIncludeAsProperty(JsonInclude.Value
.construct(JsonInclude.Include.NON_NULL, null));
return objectMapper;
}
<小时/>
调整后的示例如下所示:
<小时/>public class OptionalObjectMappingTest {
public static class MyBean {
public Integer one;
public Optional<Integer> two;
public Optional<Integer> three;
public Optional<Integer> four;
}
private ObjectMapper initObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper()
.registerModule(new Jdk8Module())
.setSerializationInclusion(JsonInclude.Include.ALWAYS);
objectMapper.configOverride(Optional.class)
.setIncludeAsProperty(JsonInclude.Value
.construct(JsonInclude.Include.NON_NULL, null));
return objectMapper;
}
@Test
public void testRoundTrip() throws Exception {
String originalJson = "{\"one\":null,\"two\":2,\"three\":null}";
ObjectMapper mapper = initObjectMapper();
MyBean bean = mapper.readValue(originalJson, MyBean.class);
String resultingJson = mapper.writeValueAsString(bean);
// SUCCESS: no "four:null" field is being added
Assert.assertEquals(originalJson, resultingJson);
}
}
<小时/>
jackson-databind 版本 2.9.0 之前的解决方法
一个可行的解决方案是覆盖 JacksonAnnotationIntrospector
并将其设置在 ObjectMapper
上。
只需包含自定义内省(introspection)器类并将 initObjectMapper()
方法更改为以下内容,给定的测试就会成功:
public static class OptionalAwareAnnotationIntrospector
extends JacksonAnnotationIntrospector {
@Override
public JsonInclude.Value findPropertyInclusion(Annotated a) {
if (Optional.class.equals(a.getRawType())) {
return JsonInclude.Value.construct(JsonInclude.Include.NON_NULL, JsonInclude.Include.NON_NULL);
}
return super.findPropertyInclusion(a);
}
}
private ObjectMapper initObjectMapper() {
return new ObjectMapper()
.registerModule(new Jdk8Module())
.setSerialisationInclusion(JsonInclude.Include.ALWAYS)
.setAnnotationIntrospector(new OptionalAwareAnnotationIntrospector());
}
关于java - Jackson:特定类型的所有属性都有不同的 JsonIninclude (例如可选),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41811931/