具有复杂键的地图的 Genson 序列化

Genson serialization for maps with complex keys

Genson 主页上列出的功能之一是 "Serialization and Deserialization of maps with complex keys".

虽然我正在尝试将具有键的地图序列化为复杂的 java 对象到 json 字符串,然后将它们反序列化回 java 地图。反序列化的映射键始终是字符串。 有人可以帮助我如何使用 genson 进行如此复杂的键映射序列化和反序列化吗?

这是我的代码

    Genson genson = new GensonBuilder().useClassMetadata(true).useRuntimeType(true).create();
    VO vo = new VO();
    Key key = new Key(18314212, new Timestamp(System.currentTimeMillis()),new Timestamp(System.currentTimeMillis()));
    vo.setEndTime(new Timestamp(System.currentTimeMillis()));
    vo.setStartTime(new Timestamp(System.currentTimeMillis()));
    vo.setItemID(18314212);
    vo.setKey(key);
    Map<Object, Object> map = new HashMap<Object, Object>();
    map.put(key, vo);
    String json  = genson.serialize(map);
    System.out.println(json); //the json map key does not have @Class attribute 
    Map jsonMap =  genson.deserialize(json, Map.class);
    System.out.println(jsonMap);

有几件事你必须知道,json 不允许不是字符串的键。 所以 Genson 将做以下两件事之一:

  • 如果键是某种基本类型(如原始类型),它将把它作为字符串提供
  • 如果密钥是一个复杂的对象,就像您的情况一样,它将作为: [{键:{},值:{}}]

现在看来,当类型未知时,它会在键上使用 toString 方法,我已经打开了一个 issue here

所以在你的情况下,解决方法是像这样输入地图:

genson.serialize(m, new GenericType<Map<Key, Value>>(){});
genson.deserialize(json, new GenericType<Map<Key, Value>>(){});

但是请注意,您还需要在 GensonBuilder 中禁用 runtimeType。因为当你启用它时,它会在序列化期间忽略定义的类型。