JAX-RS – 没有根节点的JSON

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

{ "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-RSfunction而不使用根节点生成JSON,而不是实现特定function? 我的代码需要可以在任何appserver上移植。

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

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

   RESTful Services com.sun.jersey.spi.container.servlet.ServletContainer  com.sun.jersey.config.property.resourceConfigClass com.sun.jersey.api.core.PackagesResourceConfig   com.sun.jersey.config.property.packages you.service.packages;org.codehaus.jackson.jaxrs   1   RESTful Services /your/rest/path/*  

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

 function consumesCity(json) { ... } 

更换

 ... consumesCity(json) ... 

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

好问题。 我有类似的要求。 我必须能够访问生成的原始响应并进行一些操作。 我通过注册谐振滤波器然后调整自定义响应编写器来实现这一点。 请参阅以下链接了解更多详情。

 http://www.mentby.com/paul-sandoz/access-to-raw-xml-in-jersey.html 

在您的响应filter中,您可以从生成的json中剪切出类名,或者更好的是,返回String作为响应并使用自定义的json序列化机制,如Google-gson。

如果此解决方案有效,请告诉我。

Kim Burgaard的回答以上也适用于Jersey Spring WS。 我使用Glassfish 3.0遇到了同样的问题并解决了它添加如下所示的参数。

示例web.xml

    contextConfigLocation classpath:applicationContext.xml   org.springframework.web.context.ContextLoaderListener   org.springframework.web.context.request.RequestContextListener   Jersey Spring Web Application com.sun.jersey.spi.spring.container.servlet.SpringServlet  com.sun.jersey.config.property.packages org.codehaus.jackson.jaxrs     Jersey Spring Web Application /services/*   

示例applicationContext.xml