如何在一行代码中配置JacksonJaxbJsonProvider?

时间:2013-02-05 10:11:55

标签: java json jaxb jackson

我在这样的REST应用程序中使用Jackson进行JSON序列化:

import javax.ws.rs.core.Application;

import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider;
import org.codehaus.jackson.map.SerializationConfig;

public class MyApplication extends Application {

    public Set<Class<?>> getClasses() {
        Set<Class<?>> classes = new HashSet<Class<?>>();
        classes.add(MyResource1.class);
        classes.add(MyResource2.class);
        ...
        return classes;
    }

    public Set<Object> getSingletons() {
        Set<Object> singletons = new HashSet<Object>();
        singletons.add(new JacksonJaxbJsonProvider().configure(
            SerializationConfig.Feature.WRITE_NULL_PROPERTIES, false)); // (*)
        return singletons;
    }

}

(*)否则,使用@XmlElementRef注释的字段在null(不显示)时将在JSON输出中显示为"myField": null,而对于使用@XmlElement注释的字段则可以。

然而,SerializationConfig.Feature.WRITE_NULL_PROPERTIES的使用已弃用,有利于SerializationConfig.setSerializationInclusion(..)(1) 它本身被弃用,而不是SerializationConfig.withSerializationInclusion(..)通过ObjectMapper配置(2)

但我认为使用new JacksonJaxbJsonProvider().configure(..)完成的确实是在配置一个ObjectMapper(我看了一下代码)。

所以我的问题是:如何在不使用任何弃用属性且没有(重新)创建新配置类的情况下正确配置它?

(1)http://jackson.codehaus.org/1.9.4/javadoc/org/codehaus/jackson/map/SerializationConfig.Feature.html#WRITE_NULL_PROPERTIES

(2)http://jackson.codehaus.org/1.9.4/javadoc/org/codehaus/jackson/map/SerializationConfig.html#setSerializationInclusion(org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion)

1 个答案:

答案 0 :(得分:4)

我使用下一个配置和OM:

public class JaxbJacksonObjectMapper extends ObjectMapper {

    public JaxbJacksonObjectMapper() {
        configure(Feature.WRAP_ROOT_VALUE, false); // IMPORTANT must be false
        configure(Feature.WRITE_EMPTY_JSON_ARRAYS, true);
        configure(Feature.WRAP_EXCEPTIONS, true);
        configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        final AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();

        super.getSerializationConfig().withSerializationInclusion(Inclusion.ALWAYS);
        super.getDeserializationConfig()
                .withAnnotationIntrospector(introspector);
        super.getSerializationConfig()
                .withAnnotationIntrospector(introspector);

    }

}

希望有所帮助

UPD: 对不起,我忘记了下一部分。您还需要注册,例如:

@Provider
public final class ReContextResolver implements ContextResolver<ObjectMapper> {

    private final ObjectMapper jacksonObjectMapper;

    public ReContextResolver() throws Exception {
        jacksonObjectMapper = new JaxbJacksonObjectMapper();
    }

    @Override
    public ObjectMapper getContext(final Class<?> objectType) {
        return jacksonObjectMapper;
    }

}

你可以将它组合在一个类中,就像我一样 - 我使用POJO映射和直接解析,所以对我来说它更好。