我正在尝试在RestEasy中配置jackson-module-jaxb-notiontions-2.2.1以在Json中输出空数组。
我用下一个代码来做它们:
@Provider
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class JacksonIncludeNullJsonProvider extends JacksonJaxbJsonProvider
{
public JacksonIncludeNullJsonProvider() {
ObjectMapper mapper = new ObjectMapper();
configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, true);
mapper.getSerializationConfig().withSerializationInclusion(JsonInclude.Include.ALWAYS);
super.setMapper(mapper);
}
}
但是当我用这个类编译项目时,所有JAXB注释都停止工作。
据我所知,当我在自己的提供程序中注册映射器时,它会清空JacksonJaxbJsonProvider中的所有默认设置。JAXB注释空数组包含必须正确工作的配置是什么?
默认情况下,在示例中的构造函数中创建的对象映射器未配置为支持JAXB注释。您应该重用JacksonJaxJsonProvider超类提供的内部映射器,或者配置映射器以支持JAXB注释。这是Jackson JAX-RSwiki中的链接。
这是一个基于问题的JacksonJaxJsonProvider子类示例,它在构造函数中自定义内部对象映射器(虽然不是很优雅的解决方案)。
请注意,我已经反转了原始问题的序列化设置,因为它们不会更改默认值以显示来自不同提供程序的输出的差异。
public class JacksonProvider {
public static class JacksonIncludeNullJsonProvider extends JacksonJaxbJsonProvider
{
public JacksonIncludeNullJsonProvider() {
// must be the first call to initialize the mapper
configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false);
_mapperConfig.getConfiguredMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
}
public static class Bean {
@XmlElement(name = "xmlField1")
public final String field1;
public final String field2;
public final String field3 = null;
public final Map<String, Object> field4 = Collections.emptyMap();
public Bean(String field1, String field2) {
this.field1 = field1;
this.field2 = field2;
}
}
public static void main(String[] args) throws IOException {
JacksonIncludeNullJsonProvider provider = new JacksonIncludeNullJsonProvider();
JacksonJaxbJsonProvider provider2 = new JacksonJaxbJsonProvider();
Bean bean = new Bean("a", "b");
provider.writeTo(bean, Bean.class, null, null, MediaType.APPLICATION_JSON_TYPE, null, System.out);
System.out.println();
provider2.writeTo(bean, Bean.class, null, null, MediaType.APPLICATION_JSON_TYPE, null, System.out);
}
}
输出:
{"xmlField1":"a","field2":"b"}
{"xmlField1":"a","field2":"b","field3":null,"field4":{}}