簡體   English   中英

在Jackson / Jaxb中解包元素

[英]Unwrap a element in Jackson/Jaxb

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

假設我有一個如下課程:

@XmlRootElement
public class A {
    public String s;
}

這是我使用類的jersey方法:

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

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

第二個不是。

您可以嘗試在相關的<servlet>節點下將以下內容添加到web.xml中:

<init-param>
    <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
    <param-value>true</param-value>
</init-param>

Jersey文檔提供了有關此設置的更多信息。

此功能在Jersey 1.4中引入,並取決於Jackson。 如果您使用的是Glassfish 3.0.1或更低版本隨附的版本,則需要遵循升級說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM