且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Jersey:无法从字符串中反序列化 ArrayList 的实例

更新时间:2022-06-05 17:09:11

经过漫长的一天,又过了一天……在阅读了大量 wiki 和常见问题之后,它终于奏效了.

After a long day, and another... after reading lots of wikis and faqs, it finally works.

我做了什么:

  1. 使用杰克逊
  2. 强制使用 Jackson 提供程序
  3. 定义自定义反序列化器
  4. 激活 ACCEPT_SINGLE_VALUE_AS_ARRAY 标志
  5. 修复依赖

故事:

我使用的是 Jersey 1.13,它默认使用(我相信)jaxb.

I was using Jersey 1.13 that uses (I belive) jaxb by default.

我将其更改为使用 Jackson

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

如下所述:

https://***.com/a/13895768/660990

这让我的球衣使用了jackson,但问题依旧;jackson 还不能对数组进行反序列化.

This made my jersey use jackson, but the problem remains; jackson can't deserializer the array yet.

我强制使用了 Jackson 提供程序:

<init-param>
    <param-name>com.sun.jersey.config.property.packages</param-name>
    <param-value>
        your.project.packages;
        org.codehaus.jackson.jaxrs</param-value>
</init-param>

https://***.com/a/3143214/660990

是必要的步骤,但还不够.必须激活 ACCEPT_SINGLE_VALUE_AS_ARRAY 标志.

Was a needed step, but not enough. It's necessary to activate the ACCEPT_SINGLE_VALUE_AS_ARRAY flag.

ObjectMapper objectMapper;
objectMapper = new ObjectMapper().configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

我需要定义自定义解串器

public class MyResolver implements ContextResolver<ObjectMapper> {

@Override
    public ObjectMapper getContext(final Class<?> objectType) {
        ...            
        return objectMapper;
    }
}

为了做到这一点:

Customizing-ObjectMapper

做完这些还是不行...

After doing all of this it still didn't work...

经过一段时间的搜索,我发现:

After some more search time, I found:

Jackson 2.0 和 Jersey 1.12

讨论依赖问题..

这解决了我的问题,Jersey v1.13 附带 Jackson v1.9.2 我需要 Jackson v2.0

This reveled my problem, Jersey v1.13 ships with Jackson v1.9.2 I need Jackson v2.0

我删除了 jersey-json 的依赖,因为它包含 jackson 1.9.2:

I removed dependency for jersey-json, because it included jackson 1.9.2:

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
</dependency>

并直接声明依赖于:

<dependency>
    <groupId>com.fasterxml.jackson.jaxrs</groupId>
    <artifactId>jackson-jaxrs-json-provider</artifactId>
</dependency>

参考:

jackson-jaxrs-json-provider

注意:此更改删除了泽西岛使用 Jaxb 或抛弃的能力.

Note: this change removes the Jersey ability to use Jaxb or jettison.

离题,可能对某人感兴趣:

配置 Jersey/Jackson不要将@XmlElement 字段注释用于 JSON 字段命名