JAX-RS - 没有根节点的JSON

Otá*_*cia 6 java json jax-rs

我有一个安静的Web服务,响应是:

{
    "cities": [{
        "id": "1",
        "name": "City 01",
        "state": "A1"
    }, {
        "id": "2",
        "name": "City 02",
        "state": "A1"
    }]
}
Run Code Online (Sandbox Code Playgroud)

但我想要这个:

{
    [{
        "id": "1",
        "name": "City 01",
        "state": "A1"
    }, {
        "id": "2",
        "name": "City 02",
        "state": "A1"
    }]
}
Run Code Online (Sandbox Code Playgroud)

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

Kim*_*ard 4

我在使用 Glassfish v3 时也遇到了同样的问题。我发现这种行为取决于 JAX-RS 实现,切换到 Codehaus 的 Jackson JAX-RS 实现为我解决了这个问题。

如果您也使用 Glassfish,那么您可以通过添加org.codehaus.jackson.jaxrs到您的 war 以及WEB-INF/web.xml配置中来解决问题,如下所示:

<!-- 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>
Run Code Online (Sandbox Code Playgroud)

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

function consumesCity(json) {
   ...
}
Run Code Online (Sandbox Code Playgroud)

代替

... consumesCity(json) ...
Run Code Online (Sandbox Code Playgroud)

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

... consumesCity(preprocess(json)) ...
Run Code Online (Sandbox Code Playgroud)

  • 我的印象是,这种特定行为是特定于供应商的,即集合返回类型的顶级 JSON 对象是数组,还是具有包含集合成员的字段的单个对象。看到 Glassfish 的参考实现返回后一种集合样式,我感到有点沮丧。我认为返回 JSON 数组更直观。如果您找到更好的解决方案,请发布更新。 (3认同)