本文介绍了在Jackson / Jaxb中打开一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using Jersey+Jackon to make a REST API which works with JSON.

假设我有一个类如下:

@XmlRootElement
public class A {
    public String s;
}

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

and here is my jersey method which uses the class:

@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"}]

我该怎么办?
请帮助我。

What should I do?Please help me.

推荐答案

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

Your requirement seems to be to drop the root element from json string. This can be configured in Jersey as follows.In Jersey, whether dropping root element is configured by JSONConfiguration.rootUnwrapping(). More details can be found in JSON support in Jersey and CXF.

以下是执行此操作的示例代码。

Here's a sample code that does this.

   @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;
       }
   }

这篇关于在Jackson / Jaxb中打开一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 04:08