gpt4 book ai didi

generics - Jackson 使用构建器对泛型类型进行反序列化

转载 作者:行者123 更新时间:2023-12-02 21:37:35 25 4
gpt4 key购买 nike

我正在使用 Jackson 2.2.3。我有一个通用类型,我想从 JSON 反序列化它。我在编译时知道泛型类型的类型参数。当我使用创建者反序列化或使用 setter 反序列化时,我没有任何问题。但是,当我尝试使用构建器进行反序列化时,反序列化中使用的类型参数是 LinkedHashMap,而不是请求的类型。

我认为我理解为什么 Jackson 无法确定用于构建器的所需类型参数,因此无法创建所需的参数化类型。那么,如何使用具有泛型类型的构建器呢?提示 jackson 使用哪种类型参数的最直接方法是什么?

这是我想做的一个玩具示例。

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.io.IOException;

public class Main {
public static class DesiredTypeArgument {}

@JsonDeserialize(builder = GenericType.Builder.class)
public static class GenericType<T> {
private final T t;

private GenericType(final T t) {
this.t = t;
}

public T getT() {
return t;
}

public static class Builder<T> {
private T t;

public GenericType<T> build() {
return new GenericType<>(t);
}

public Builder<T> withT(final T t) {
this.t = t;
return this;
}
}
}

public static void main(String[] args) throws IOException {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
final GenericType<DesiredTypeArgument> x = new GenericType.Builder<DesiredTypeArgument>()
.withT(new DesiredTypeArgument())
.build();
final String json = objectMapper.writeValueAsString(x);
final GenericType<DesiredTypeArgument> y = objectMapper.readValue(json,
objectMapper.getTypeFactory().constructParametricType(GenericType.class, DesiredTypeArgument.class));
System.out.println("type argument = " + ((Object) y.getT()).getClass());
}
}

最佳答案

我不确定您是否必须编写自定义反序列化器。如果我理解你的用例,你可以这样做:

static public <T extends Inflatable> List<T> readObjects(List<T> listType, String recType){
Class c = Class.forName("sfshare." + recType);
JavaType type = mapper.getTypeFactory().constructParametricType(Result.class, c);
Result<T> res = mapper.readValue(rspData, type);
}

关于generics - Jackson 使用构建器对泛型类型进行反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19393023/

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