FrV*_*aBe 14 java json jersey jackson
我正在运行Jersey REST服务.代表我的资源的POJO是JAXB(XML)带注释的简单Java类(它们是从模式定义生成的 - 因此它们具有注释).
我希望Jersey/Jackson忽略XML-Annotations.我在我的web.xml中做了这个配置(如这里提到的):
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
Run Code Online (Sandbox Code Playgroud)
我现在预计@ZMLElement注释将不再用于JSON字段命名策略.
但是看看这个java字段(成员)
@XmlElement(name = "person", required = true)
protected List<Person> persons;
Run Code Online (Sandbox Code Playgroud)
我仍然得到以下JSON表示:
....,"person":[{"name":"FooBar", ....... (person without the 's')
Run Code Online (Sandbox Code Playgroud)
所有其他字段仍然从@XmlElement注释中获取其JSON名称,而不是从Java字段名称获取.
我想实现杰克逊完整数据绑定(POJO)示例中描述的JSON输出.
它在这样的简单测试中工作正常(使用我的XML注释类):
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(System.out, myObject);
Run Code Online (Sandbox Code Playgroud)
但嵌入在泽西岛我没有得到预期的JSON输出.
他们在Jersey中的其他配置选项是否获得"简单"POJO JSON表示(因为这最适合必须反序列化JSON结果的客户端).
谢谢克劳斯
详细解决方案
(1)ContextResolver
为Jacksons 实现一个ObjectMapper
创建不使用注释的ObjectMapper的Jacksons .
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;
}
}
Run Code Online (Sandbox Code Playgroud)
(2)在application.xml中注册ContextResolver Spring bean
<bean class="foo.bar.jackson.JacksonContextResolver"/>
Run Code Online (Sandbox Code Playgroud)
在低级别,需要确保ObjectMapper不使用JAXBAnnotationIntrospector,而只使用默认的JacksonAnnotationIntrospector.我认为您应该能够构建ObjectMapper(默认情况下不添加JAXB introspector),并通过标准的JAX-RS提供程序机制进行注册.这应该覆盖POJO映射器功能否则将构造的ObjectMapper.
归档时间: |
|
查看次数: |
19446 次 |
最近记录: |