RestEasy + JacksonJaxbJsonProvider配置包含+注释

时间:2014-05-26 18:03:36

标签: java json jaxb jackson

我正在尝试在RestEasy中为json中的输出空数组配置jackson-module-jaxb-annotations-2.2.1。

我使用下一个代码执行它们:

@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注释都停止工作。

据我所知,当我在我自己的提供商中注册mapper时,它会清空JacksonJaxbJsonProvider中的所有默认settigs。 JAXB注释+空数组包含必须正常配置?

1 个答案:

答案 0 :(得分:0)

默认情况下,示例中构造函数中创建的对象映射器未配置为支持JAXB注释。您应该重新使用JacksonJaxJsonProvider超类提供的内部映射器,或者配置映射器以支持JAXB注释。以下是the Jackson JAX-RS wiki.

的链接

这是一个基于问题的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":{}}