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

wil*_*lvv 26 java ajax json jersey

我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)

代码正确执行,数据返回给客户端(jQuery ajax调用).问题是如果"result"数组有一个元素或多个元素,则返回数据的格式会发生变化.

回复一个元素:

{"fileInfo":{"fileName":"weather.arff","id":"10"}}
Run Code Online (Sandbox Code Playgroud)

回应有两个要素:

{"fileInfo":[{"fileName":"weather.arff","id":"10"},{"fileName":"supermarket.arff","id":"11"}]}
Run Code Online (Sandbox Code Playgroud)

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

{"fileInfo":[{"fileName":"weather.arff","id":"10"}]}
Run Code Online (Sandbox Code Playgroud)

即一个内部有一个对象的数组?

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

谢谢你的时间.

wil*_*lvv 12

我最终使用了杰克逊,也在泽西官方文档(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支持

    <init-param>
          <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
          <param-value>true</param-value>
    </init-param>
Run Code Online (Sandbox Code Playgroud)

瞧!


sec*_*ing 5

如果您使用JAXB来构建JSON结果,则可以配置Jersey JSON处理器以获得更重要的JSON格式.

泽西官方文档有详细的配置:

要实现更重要的JSON格式更改,您需要配置Jersey JSON处理器本身.可以在JSONConfiguration实例上设置各种配置选项.然后可以进一步使用该实例来创建JSONConfigurated JSONJAXBContext,它充当该区域中的主要配置点.要将专门的JSONJAXBContext传递给Jersey,您最终需要实现一个JAXBContext ContextResolver:

    @Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {
    private final JAXBContext context;
    private final Set<Class> 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;
    }
}
Run Code Online (Sandbox Code Playgroud)


Fab*_*nge 0

您可以使用 Jettison(随 Jersey 一起提供)并准备您希望自己使用JSONObjectJSONArray作为返回值的结构。它们位于包中org.codehaus.jettison.json,其jettison-1.3.2.jar具有传递依赖关系jerysey-json