gpt4 book ai didi

java - 使用 GSON 反序列化为 ImmutableMap

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:55:04 28 4
gpt4 key购买 nike

我想使用 GSON 来反序列化:

"starterItems": {
"Appeltaart": 3,
"Soap_50": 3
}

...进入 Guava ImmutableMap:

private ImmutableMap<String,Integer> starterItems;

我以为我会使用常规的 GSON 映射解析,然后制作结果的不可变副本,如下所示:

    gb.registerTypeAdapter(ImmutableMap.class, new JsonDeserializer<ImmutableMap>() {
@SuppressWarnings("unchecked")
@Override public ImmutableMap deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return ImmutableMap.copyOf((Map) context.deserialize(json, Map.class));
}
});

但不出所料,这太简单了(没有类型信息)。我收到错误:

com.google.gson.JsonParseException: The JsonDeserializer MapTypeAdapter failed to deserialized json object {"Appeltaart":3,"Soap_50":3} given the type interface java.util.Map

我可以做我想做的事吗?

最佳答案

这并不是那么简单,因为您可能希望维护类型参数以构建包含正确类型的映射。为此,您可以使用 TypeAdapterFactory , 并在那里要求代表 TypeAdapter , 使用完全指定的 TypeToken .

public class ImmutableMapTypeAdapterFactory implements TypeAdapterFactory {

public static final ImmutableMapTypeAdapterFactory INSTANCE = new ImmutableMapTypeAdapterFactory();

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!ImmutableMap.class.isAssignableFrom(type.getRawType())) {
return null;
}
final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
return new TypeAdapter<T>() {
@Override
public void write(JsonWriter out, T value) throws IOException {
delegate.write(out, value);
}

@Override
@SuppressWarnings("unchecked")
public T read(JsonReader in) throws IOException {
return (T) ImmutableMap.copyOf((Map) delegate.read(in));
}
};
}
}

现在你有另一个问题:默认的 GSON MapTypeAdapterFactory将尝试创建 ImmutableMap 的实例, 并进行修改。这显然行不通。你应该创建一个 TypeToken<HashMap<K, V>>来自 TypeToken<ImmutableMap<K, V>> ,但老实说,我不知道你该怎么做。相反,您可以使用 InstanceCreator欺骗 GSON 构建一个 HashMapImmutableMap实际上是必需的:

public static <K,V> InstanceCreator<Map<K, V>> newCreator() {
return new InstanceCreator<Map<K, V>>() {
@Override
public Map<K, V> createInstance(Type type) {
return new HashMap<K, V>();
}
};
}

显然,您必须同时注册 TypeAdapterFactory 和 InstanceCreator:

GsonBuilder b = new GsonBuilder();
b.registerTypeAdapterFactory(new ImmutableMapTypeAdapterFactory());
b.registerTypeAdapter(ImmutableMap.class, ImmutableMapTypeAdapterFactory.newCreator());

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

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