简体   繁体   English

GSON包装类的反序列化

[英]GSON de/serialization of wrapper class

I have a convenience class wrapper for a Map, that looks something like this: 我有一个Map的便捷类包装,看起来像这样:

class MapWrapper {
    private Map<String, Integer> wrapped = new HashMap<>();

    public void add(String key, Integer count) {/*implementation*/}
    // Other modifiers
}

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. 我之所以不直接使用Map而是使用包装器,是因为我需要使用方法间接访问Map。

When I de/serialize this object, I would like the JSON to serialize as if the wrapper class wasn't there. 当我反序列化此对象时,我希望对JSON进行序列化,就像包装类不在那里一样。 EG I want: 我想要的EG:

{
  "key1":1,
  "key2":2
}

for my JSON in/output and not (what is the default just passing to GSON): 用于我的JSON输入/输出而不是(仅传递给GSON的默认值):

{
  wrapped: {
    "key1":1,
    "key2":2
  }
}

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. 如果很重要,则该对象将包含在另一个对象中,因此GSON上下文反序列化将能够说该对象是MapWrapper而不只是Map。

Implement a custom JsonSerializer / JsonDeserializer for your type: 为您的类型实现定制的JsonSerializer / JsonDeserializer:

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;
    }
}

Then register it when you construct your Gson instance: 然后在构造Gson实例时注册它:

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());
}

This should print: 这应该打印:

{"key1":1,"key2":2}
key1, 1
key2, 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM