且构网

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

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

更新时间:2022-02-13 22:44:36

经过漫长的一天,又...阅读了大量的 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.

我把它改成了使用杰克逊

<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 还不能对数组进行反序列化.

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

注意:此更改移除了 Jersey 使用 Jaxb 或 jettison 的能力.

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

题外话,可能有人感兴趣:

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