GSON de/包装类的序列化 [英] GSON de/serialization of wrapper class
问题描述
我有一个Map的便捷类包装,看起来像这样:
I have a convenience class wrapper for a Map, that looks something like this:
class MapWrapper {
private Map<String, Integer> wrapped = new HashMap<>();
public void add(String key, Integer count) {/*implementation*/}
// Other modifiers
}
我之所以不直接使用Map而是使用包装器,是因为我需要使用方法间接访问Map.
The reason that I'm not using a Map directly but rather the wrapper is because I need to use the methods to access the Map indirectly.
当我反序列化此对象时,我希望对JSON进行序列化,就像没有包装类一样.例如.我想要:
When I de/serialize this object, I would like the JSON to serialize as if the wrapper class wasn't there. E.G. I want:
{
"key1":1,
"key2":2
}
不是我的JSON输入/输出(默认是传递给GSON的默认值):
for my JSON in/output and not (what is the default just passing to GSON):
{
wrapped: {
"key1":1,
"key2":2
}
}
如果重要的话,该对象将包含在另一个对象中,因此GSON上下文反序列化将能够说该对象是MapWrapper而不只是Map.
If it matters, this object will be contained within another so GSON contextual deserialization will be able to say that the Object is a MapWrapper and not just a Map.
推荐答案
为您的类型实现自定义JsonSerializer/JsonDeserializer:
Implement a custom JsonSerializer / JsonDeserializer for your type:
public class MyTypeAdapter implements JsonSerializer<MapWrapper>, JsonDeserializer<MapWrapper> {
@Override
public JsonElement serialize(MapWrapper src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject obj = new JsonObject();
src.wrapped.entrySet().forEach(e -> obj.add(e.getKey(), new JsonPrimitive(e.getValue())));
return obj;
}
@Override
public MapWrapper deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
MapWrapper wrapper = new MapWrapper();
json.getAsJsonObject().entrySet().forEach(e -> wrapper.wrapped.put(e.getKey(), e.getValue().getAsInt()));
return wrapper;
}
}
然后在构造Gson实例时注册它:
Then register it when you construct your Gson instance:
Gson gson = new GsonBuilder()
.registerTypeAdapter(MapWrapper.class, new MyTypeAdapter())
.create();
您应该可以这样称呼它:
You should be able to call it like so:
MapWrapper wrapper = new MapWrapper();
wrapper.wrapped.put("key1", 1);
wrapper.wrapped.put("key2", 2);
String json = gson.toJson(wrapper, MapWrapper.class);
System.out.println(json);
MapWrapper newWrapper = gson.fromJson(json, MapWrapper.class);
for(Entry<String, Integer> e : newWrapper.wrapped.entrySet()) {
System.out.println(e.getKey() + ", " + e.getValue());
}
这应该打印:
{"key1":1,"key2":2}
key1, 1
key2, 2
这篇关于GSON de/包装类的序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!