使用ObjectMapper反序列化到参数化的类上时,即使使用TypeReference和TypeFactory时也发生ClassCastException

时间:2019-02-25 22:56:28

标签: java generics jackson deserialization type-erasure

当尝试使用ObjectMapper反序列化到参数化的类时,我得到以下异常(对于非参数化的类工作正常):

java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class com.xyz.A (java.util.LinkedHashMap is in module java.base of loader 'bootstrap'; com.xyz.A is in unnamed module of loader 'app')

这是原始代码:

Foo<A> request = OBJECT_MAPPER.readValue(payload, Foo.class);

我尝试过:

Foo<A> request = OBJECT_MAPPER.readValue(payload, new TypeReference<Foo<A>>() {});

以及:

JavaType myType = OBJECT_MAPPER.getTypeFactory()
    .constructParametricType(Foo.class, A.class);
Foo<A> request = OBJECT_MAPPER.readValue(payload, myType);

但是我仍然遇到同样的异常。

我的场景中是否存在一些这些问题未涵盖的特殊之处?

我能想到的一件事是,我的Foo实际上是一个生成类的带有@AutoMatter注释的接口:

@AutoMatter
public interface Foo<T> {
  Optional<T> parent;
  Optional<List<T>> children;
}

通常,映射到AutoMatter生成的类通常没有问题。只是添加了似乎引起问题的参数化<T>

有人有主意吗?


编辑以回答@MichalZiober的问题:

在我的测试代码中,我实际上只是序列化我知道的有效对象,即 。然后反序列化以取回我开始使用的对象:

Foo<A> myExampleObject;
ByteString.encodeUtf8(OBJECT_MAPPER.writeValueAsString(myExampleObject));

编辑2

好的,看来我们已经在导入该模块:

  @VisibleForTesting
  public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
      .registerModule(new JodaModule())
      .registerModule(new GuavaModule())
      .registerModule(new AutoMatterModule())
      .registerModule(new Jdk8Module())
      .registerModule(new ProtobufModule())
      .setSerializationInclusion(JsonInclude.Include.NON_NULL)
      .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
      .configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false)
      .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
      .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

2 个答案:

答案 0 :(得分:1)

Optional结构中使用POJO时,需要从jackson-modules-java8启用Jdk8Module。下面的示例显示了注册该模块后,我们可以对数据进行序列化和反序列化:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import io.norberg.automatter.AutoMatter;
import io.norberg.automatter.jackson.AutoMatterModule;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.registerModule(new AutoMatterModule());
        mapper.registerModule(new Jdk8Module());

        String json = "{\"parent\":\"Aaaa\", \"children\":[\"a\"]}";
        System.out.println(mapper.readValue(json, Foo.class));


        Foo<StringWrapper> foo = new FooBuilder<StringWrapper>()
                .parent(new StringWrapperBuilder().value("PARENT").build())
                .children(Arrays.asList(new StringWrapperBuilder().value("CHILD1").build()))
                .build();
        json = mapper.writeValueAsString(foo);
        System.out.println(json);
        System.out.println(mapper.readValue(json, Foo.class));
    }
}
@AutoMatter
interface Foo<T> {
    Optional<T> parent();
    Optional<List<T>> children();
}

@AutoMatter
interface StringWrapper {
    String value();
}

上面的代码显示:

Foo{parent=Optional[Aaaa], children=Optional[[a]]}
{
  "parent" : {
    "value" : "PARENT"
  },
  "children" : [ {
    "value" : "CHILD1"
  } ]
}
Foo{parent=Optional[{value=PARENT}], children=Optional[[{value=CHILD1}]]}

答案 1 :(得分:0)

现在我只需要放弃参数化。我只有这么多的课程,

Foo<A>
Foo<B>
Foo<C>

只显式地创建每个对象会更容易:

@AutoMatter
public interface FooA {
  A parent;
  List<A> children;
}

@AutoMatter
public interface FooB {
  B parent;
  List<B> children;
}

@AutoMatter
public interface FooC {
  C parent;
  List<C> children;
}

(我也意识到Optional是不必要的。)

这不是真正的答案,所以不接受。