gpt4 book ai didi

java - 使用 Jackson 反序列化泛型

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:09:45 25 4
gpt4 key购买 nike

我正在尝试创建一个使用 Jackson 反序列化 POJO 的类。

看起来像这样......

public class DeserialiserImp<T> implements Deserialiser<T> {

protected ObjectMapper objectMapper = new ObjectMapper();

@Override
public T get(String content, Class clazz) throws IOException {
return (T) objectMapper.readValue(content, clazz);
}

@Override
public List<T> getList(String content, Class clazz) throws IOException {
return objectMapper.readValue(content, TypeFactory.collectionType(ArrayList.class, clazz));
}

}

我有 2 个关于此实现的问题。

首先是我将类类型传递给方法,以便对象映射器知道应该反序列化的类型。有没有更好的方法使用泛型?

同样在 get 方法中,我将从 objectMapper 返回的对象转换为 T。这看起来特别讨厌,因为我必须在这里转换 T,然后我还必须从方法转换对象类型调用它。

我在这个项目中使用 Roboguice,所以如果我可以通过注入(inject)更改类型然后注释我需要它返回的通用类型的对象,那就太好了。我读到了 TypeLiteral并想知道它是否可以解决这个问题?

最佳答案

The first is that I am passing the class type into the methods so the objectmapper knows the type that should deserialize. Is there a better way using generics?

不幸的是不是,这是因为类型删除。

Also in the get method I am casting an object returned from the objectMapper to T. This seems particularly nasty way of doing it as I have to cast T here and then I have to also cast the object type from the method which is calling it.

改为这样做:

@Override
public T get(String content, Class<T> clazz) throws IOException {
return objectMapper.readValue(content, clazz);
}

I am using Roboguice in this project so it would be nice if I could change the type through injection and then annotate the object which the Generic type I need it to return. I read about TypeLiteral and wondering if it could solve this problem?

我不太明白你想达到什么目的,但既然你无论如何都需要通过这门课,那还有可能吗?

关于java - 使用 Jackson 反序列化泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13118798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com