JAX-RS - 没有根节点的JSON [英] JAX-RS - JSON without root node

查看:109
本文介绍了JAX-RS - 没有根节点的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个安静的网络服务,回复是:

I have a restful web service, and the response is:

{
    "cities": [{
        "id": "1",
        "name": "City 01",
        "state": "A1"
    }, {
        "id": "2",
        "name": "City 02",
        "state": "A1"
    }]
}

但我希望如此:

{
    [{
        "id": "1",
        "name": "City 01",
        "state": "A1"
    }, {
        "id": "2",
        "name": "City 02",
        "state": "A1"
    }]
}

如何配置JAX-RS以仅使用JAX-RS功能而不使用根节点生成JSON,而不是实现特定功能?我的代码需要可以在任何appserver上移植。

How I can configure JAX-RS to produces JSON without root node using only JAX-RS feature, and not implementation specific feature? My code needs to be portable across any appserver.

推荐答案

我遇到了与Glassfish v3相同的问题。我发现这种行为取决于JAX-RS的实现,切换到Codehaus的Jackson JAX-RS实现为我解决了这个问题。

I had the same problem with Glassfish v3. I found this behavior depends on the JAX-RS implementation and switching to Codehaus' Jackson JAX-RS implementation solved the problem for me.

如果你也使用Glassfish ,然后你可以通过在战争中加入 org.codehaus.jackson.jaxrs 以及 WEB-INF / web.xml来解决问题配置如下:

If you're using Glassfish as well, then you can solve the problem by adding org.codehaus.jackson.jaxrs to your war as well as to the WEB-INF/web.xml configuration as follows:

<!-- REST -->

<servlet>
  <servlet-name>RESTful Services</servlet-name>
  <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
  <init-param>
    <param-name>com.sun.jersey.config.property.resourceConfigClass</param-name>
    <param-value>com.sun.jersey.api.core.PackagesResourceConfig</param-value>
  </init-param>
  <init-param>
    <param-name>com.sun.jersey.config.property.packages</param-name>
    <param-value>you.service.packages;org.codehaus.jackson.jaxrs</param-value>
    <!-- NOTE: The last element above, org.codehaus.jackson.jaxrs, replaces the default
       JAX-RS processor with the Codehaus Jackson JAX-RS implementation. The default
       JAX-RS processor returns top-level arrays encapsulated as child elements of a
       single JSON object, whereas the Jackson JAX-RS implementation return an array.
    -->
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>RESTful Services</servlet-name>
  <url-pattern>/your/rest/path/*</url-pattern>
</servlet-mapping>

或者,您可以简单地拦截客户端中的响应:

Alternatively, you might be able to simply intercept the response in the client:

function consumesCity(json) {
   ...
}

替换

... consumesCity(json) ...

with

function preprocess(json) {
    return json.city;
}

... consumesCity(preprocess(json)) ...

这篇关于JAX-RS - 没有根节点的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆