在 Jackson/Jaxb 中打开一个元素

2022-01-19 00:00:00 java jackson jaxb jersey

我正在使用 Jersey+Jackon 制作一个与 JSON 配合使用的 REST API.

假设我有一个类如下:

@XmlRootElement公共类 A {公共字符串;}

这是我使用该类的球衣方法:

<代码>@GET@Produces(MediaType.APPLICATION_JSON)public Object get(@PathParam("id") String id) 抛出异常{A[] a= 新 A[2];a[0] = 新的 A();a[0].s="abc";a[1] = 新的 A();a[1].s="def";返回一个;}

输出是:

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

但我希望它是这样的:

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

我该怎么办?请帮帮我.

解决方案

您的要求似乎是从 json 字符串中删除根元素.这可以在 Jersey 中进行如下配置.在 Jersey 中,是否删除根元素由 JSONConfiguration.rootUnwrapping() 配置.可以在 Jersey 和 CXF 中的 JSON 支持中找到更多详细信息..p>

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

 @Provider公共类 MyJAXBContextResolver 实现 ContextResolver{私有 JAXBContext 上下文;私有类[] 类型 = {StatusInfoBean.class, JobInfoBean.class};公共 MyJAXBContextResolver() 抛出异常 {this.context = 新的 JSONJAXBContext(JSONConfiguration.mapped().rootUnwrapping(真).arrays("工作").nonStrings("pages", "tonerRemaining").建造(),类型);}公共 JAXBContext getContext(Class<?> objectType) {返回(类型[0].equals(objectType))?上下文:空;}}

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

Assume that I have a class as follows:

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

the out put is:

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

but I want it to be like this:

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

What should I do? Please help me.

解决方案

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

相关文章