将Jersey / Jackson配置为不使用@XmlElement字段注释进行JSON字段命名

时间:2011-02-15 15:32:09

标签: java json jersey jackson

我正在运行Jersey REST服务。表示我的资源的POJO是JAXB(XML)带注释的简单Java类(它们是从模式定义生成的 - 因此它们具有注释)。

我希望Jersey / Jackson忽略XML-Annotations。我在我的web.xml中做了这个配置(如上所述here):

  <init-param>
    <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
    <param-value>true</param-value>
  </init-param>

我现在预计@ZMLElement注释将不再用于JSON字段命名策略。

但是看看这个java字段(成员)

@XmlElement(name = "person", required = true)
protected List<Person> persons;

我仍然得到以下JSON表示:

....,"person":[{"name":"FooBar", ....... (person without the 's')

所有其他字段仍然从@XmlElement注释中获取其JSON名称,而不是从Java字段名称获取。

我想实现杰克逊Full Data Binding (POJO) Example中描述的JSON输出。

它在这样的简单测试中工作正常(使用我的XML注释类):

  ObjectMapper mapper = new ObjectMapper(); 
  mapper.writeValue(System.out, myObject);

但是嵌入在Jersey中我没有得到预期的JSON输出。

Jersey中的其他配置选项是否可以获得“简单”的POJO JSON表示(因为这最适合需要反序列化JSON结果的客户端)。

谢谢克劳斯

详细解决方案

(1)为Jacksons ContextResolver实现ObjectMapper,创建一个不使用注释的ObjectMapper。

package foo.bar.jackson;

import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;

/**
 * Customized {@code ContextResolver} implementation that does not use any
 * annotations to produce/resolve JSON field names.
 */
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JacksonContextResolver implements ContextResolver<ObjectMapper> {

    private ObjectMapper objectMapper;

    /**
     * Creates a new instance.
     * 
     * @throws Exception
     */
    public JacksonContextResolver() throws Exception {
        this.objectMapper = new ObjectMapper().configure(
                DeserializationConfig.Feature.USE_ANNOTATIONS, false)
                .configure(SerializationConfig.Feature.USE_ANNOTATIONS, false);
        ;
    }

    /**
     * @see javax.ws.rs.ext.ContextResolver#getContext(java.lang.Class)
     */
    public ObjectMapper getContext(Class<?> objectType) {
        return objectMapper;
    }
}

(2)在application.xml

中注册ContextResolver Spring bean
<bean class="foo.bar.jackson.JacksonContextResolver"/>

1 个答案:

答案 0 :(得分:6)

在低级别,需要确保ObjectMapper不使用JAXBAnnotationIntrospector,而只使用默认的JacksonAnnotationIntrospector。我认为您应该能够构建ObjectMapper(默认情况下不添加JAXB introspector),并通过标准的JAX-RS提供程序机制进行注册。这应该覆盖POJO映射器功能否则将构造的ObjectMapper。

相关问题