java – 在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()配置了删除根元素.更多细节可以在
JSON support in Jersey and CXF找到.

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

   @Provider
   public class MyJAXBContextResolver implements ContextResolver<JAXBContext> {

       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;
       }
   }
点赞