Jersey:具有 1 个元素的 Json 数组被序列化为对象

Jersey: Json array with 1 element is serialized as object(Jersey:具有 1 个元素的 Json 数组被序列化为对象)

本文介绍了Jersey:具有 1 个元素的 Json 数组被序列化为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Jersey/Java 创建一个 REST 服务器,但我发现了一个奇怪的行为.

I'm creating a REST server with Jersey/Java and I found a strange behavior.

我在服务器上有一个方法,它以 Json 形式返回一个对象数组

I have a method on the server that returns an array of objects as 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 调用).问题是如果结果"数组有一个或多个元素,则返回数据的格式会发生变化.

The code is executed correctly and data is returned to the client (a jQuery ajax call). The problem is that the format of the returned data changes if the "result" array has one element or more than one.

一个元素的响应:

{"fileInfo":{"fileName":"weather.arff","id":"10"}}

包含两个元素的响应:

{"fileInfo":[{"fileName":"weather.arff","id":"10"},{"fileName":"supermarket.arff","id":"11"}]}

如您所见,在第一种情况下,返回对象的fileInfo"属性的值是一个对象,而在第二种情况下,该值是一个数组.我究竟做错了什么?第一种情况不应该返回这样的东西吗:

As you can see, in the first scenario the value of the "fileInfo" property of the returned object is an object, and in the second case the value is an array. What am I doing wrong? Shouldn't the first case return something like this:

{"fileInfo":[{"fileName":"weather.arff","id":"10"}]}

即里面只有一个对象的数组?

i.e. an array with a single object inside?

我知道我可以在客户端检测到这一点,但这似乎是一个非常丑陋的 hack.

I know that I can detect this on the client side, but it seems like a very ugly hack.

感谢您的宝贵时间.

推荐答案

我最终使用了 Jackson,在 Jersey 官方文档中也有描述 (http://jersey.java.net/nonav/documentation/latest/user-guide.html#json.pojo.approach.section).

I ended up using Jackson, also described in the official Jersey documentation (http://jersey.java.net/nonav/documentation/latest/user-guide.html#json.pojo.approach.section).

我之前尝试过,但它不起作用,因为我的项目的构建路径中没有 jackson jar(根据文档,我认为它已内置到 jersey 的核心库中).

I had tried that before but it wasn't working because I didn't have the jackson jar in the buildpath of my project (Based on the documentation I thought it was built into jersey's core library).

我刚刚添加了 jackson-all.jar 文件 (http://wiki.fasterxml.com/JacksonDownload) 并在配置中启用了 POJO 支持

I just added the jackson-all.jar file (http://wiki.fasterxml.com/JacksonDownload) and enabled the POJO support in the configuration

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

瞧!

这篇关于Jersey:具有 1 个元素的 Json 数组被序列化为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Jersey:具有 1 个元素的 Json 数组被序列化为对象

基础教程推荐