Jersey:带有1个元素的Json数组被序列化为对象
我正在使用Jersey / Java创建一个REST服务器,我发现了一个奇怪的行为。
我在服务器上有一个方法,它返回一个对象数组作为Json
@GET @Path("/files") @Produces(MediaType.APPLICATION_JSON) public Object getFiles() throws Exception{ DatabaseManager db = new DatabaseManager(); FileInfo[] result = db.getFiles(); return result; }
代码正确执行,数据返回给客户端(jQuery ajax调用)。 问题是如果“result”数组有一个元素或多个元素,则返回数据的格式会发生变化。
回复一个元素:
{"fileInfo":{"fileName":"weather.arff","id":"10"}}
回应有两个要素:
{"fileInfo":[{"fileName":"weather.arff","id":"10"},{"fileName":"supermarket.arff","id":"11"}]}
如您所见,在第一个场景中,返回对象的“fileInfo”属性的值是一个对象,在第二种情况下,值是一个数组。 我究竟做错了什么? 第一种情况不应该返回这样的东西:
{"fileInfo":[{"fileName":"weather.arff","id":"10"}]}
即一个内部有一个对象的数组?
我知道我可以在客户端检测到这一点,但这似乎是一个非常难看的黑客。
谢谢你的时间。
我最终使用了jackson,也在官方泽西岛文档(http://jersey.java.net/nonav/documentation/latest/user-guide.html#json.pojo.approach.section)中有所描述。
之前我曾经尝试过,但它没有工作,因为我的项目的构建路径中没有jackson jar(基于文档,我认为它是内置于jersey的核心库)。
我刚刚添加了jackson-all.jar文件(http://wiki.fasterxml.com/JacksonDownload)并在配置中启用了POJO支持
com.sun.jersey.api.json.POJOMappingFeature true
瞧!
如果您使用JAXB来构建JSON结果,则可以配置Jersey JSON处理器以获得更重要的JSON格式。
泽西官方文档有详细的配置:
要实现更重要的JSON格式更改,您需要配置Jersey JSON处理器本身。 可以在JSONConfiguration实例上设置各种配置选项。 然后可以进一步使用该实例来创建JSONConfigurated JSONJAXBContext,它充当该区域中的主要配置点。 要将专门的JSONJAXBContext传递给Jersey,您最终需要实现一个JAXBContext ContextResolver:
@Provider public class JAXBContextResolver implements ContextResolver { private final JAXBContext context; private final Set types; private Class[] ctypes = { FileInfo.class}; //your pojo class public JAXBContextResolver() throws Exception { this.types = new HashSet(Arrays.asList(ctypes)); this.context = new JSONJAXBContext(JSONConfiguration.natural().build(), ctypes); //json configuration } @Override public JAXBContext getContext(Class> objectType) { return (types.contains(objectType)) ? context : null; } }
还看看下面的答案,为我解决了这个问题:
如何自定义JAXB对象列表到JSON的序列化?
您可以使用Jettison(与Jersey一起使用)并准备您希望自己使用JSONObject
和JSONArray
作为返回值的结构。 它们位于org.codehaus.jettison.json
jettison-1.3.2.jar
的包org.codehaus.jettison.json
,这是jerysey-json
的传递依赖
您也可以尝试Genson库http://code.google.com/p/genson/ 。 它与jersey很好地融为一体,只需将jar放在你的类路径中,一切都会顺利进行。 它不需要你编写额外的代码,它应该像你现在的工作,但没有任何奇怪的结果。
我已经挣扎了很多,找到了这个简单的解决方案
在你的pom.xml中:
org.codehaus.jackson jackson-jaxrs 1.9.13 org.codehaus.jackson jackson-xc 1.9.13
在您的web.xml中:
com.sun.jersey.spi.container.servlet.ServletContainer com.sun.jersey.config.property.packages com.other-packages;org.codehaus.jackson.jaxrs