在Jackson / Jaxb中打开一个元素

我使用Jersey + Jackon制作一个可以与JSON一起使用的REST API。

假设我有一个如下课程:

@XmlRootElement public class A { public String s; } 

这是我使用该类的泽西方法:

 @GET @Produces(MediaType.APPLICATION_JSON) public Object get(@PathParam("id") String id) throws Exception{ A[] a= new A[2]; a[0] = new A(); a[0].s="abc"; a[1] = new A(); a[1].s="def"; return a; } 

出局是:

 {"a":[{"s":"abc"},{"s":"def"}]} 

但我希望它是这样的:

 [{"s":"abc"},{"s":"def"}] 

我该怎么办? 请帮帮我。

您的要求似乎是从json字符串中删除根元素。 这可以在Jersey中配置如下。 在Jersey中,是否通过JSONConfiguration.rootUnwrapping()配置了删除根元素。 更多细节可以在Jersey和CXF的JSON支持中找到。

这是一个执行此操作的示例代码。

  @Provider public class MyJAXBContextResolver implements ContextResolver { private JAXBContext context; private Class[] types = {StatusInfoBean.class, JobInfoBean.class}; public MyJAXBContextResolver() throws Exception { this.context = new JSONJAXBContext( JSONConfiguration.mapped() .rootUnwrapping(true) .arrays("jobs") .nonStrings("pages", "tonerRemaining") .build(), types); } public JAXBContext getContext(Class objectType) { return (types[0].equals(objectType)) ? context : null; } } 

第一个是有效的JSON字符串。

第二个不是。

您可以尝试将以下内容添加到您的web.xml,在相关的节点下:

  com.sun.jersey.api.json.POJOMappingFeature true  

Jersey文档提供了有关此设置的更多信息。

此function在Jersey 1.4中引入,取决于Jackson。 如果您使用的是Glassfish 3.0.1或更低版本捆绑的版本,则需要按照升级说明进行操作 。