1

Genson 主页上列出的功能之一是“具有复杂键的地图的序列化和反序列化”。

虽然我试图将带有 Keys 的映射作为复杂的 java 对象序列化为 json 字符串,然后将它们反序列化回 java Map。反序列化的映射键始终是字符串。有人可以帮我了解如何使用 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);
4

1 回答 1

1

您必须知道几件事,json 不允许非字符串的键。因此,Genson 将做以下两件事之一:

  • 如果键是某种基本类型(如原语),那么它将作为字符串提供
  • 如果键是一个复杂的对象,就像你的情况一样,它会将它作为: [{key:{}, value: {}}]

现在看来,当类型未知时,它将在密钥上使用 toString 方法,我在这里打开了一个问题

因此,在您的情况下,解决方法是像这样键入地图:

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

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

于 2015-05-05T16:40:38.087 回答