将Guava HashMultimap转换为json

sat*_*sat 13 json multimap gson guava

我想将HashMultiMap打印为json.

HashMultimap<String,Object> multimap = HashMultimap.create();
multimap.put("a",Obj1);
multimap.put("a",Obj3);
multimap.put("b",Obj2);
Run Code Online (Sandbox Code Playgroud)

{ 
  "a":[Obj1,Obj3],
  "b":[Obj2]
}
Run Code Online (Sandbox Code Playgroud)

Obj1和其他对象应该再次在json中(为了保持它清洁,我已经将它显示为对象)
我可以迭代各个键并使用诸如Gson之类的库将对象集转换为json.

但是要获取HashMultimap的整个快照,我想将其转换为json并检查它.

Gson无法转换整个地图,但可以做单个值(对象列表为json)

Wes*_*ley 14

首先调用asMap()MultiMap.这会将MultiMap转换为标准Map,其中每个值都是Collection.

在您的示例中,生成的Map的类型是Map<String, Collection<Object>>.Gson应该能够正确地序列化.


maa*_*nus 5

你需要写一个JsonAdapter或两个JsonDeserializerJsonSerializer.这太可怕了,但我想尝试一下.

基本上,你将一切都委托给了Map<String, Collection<V>>.

static class MultimapAdapter implements JsonDeserializer<Multimap<String, ?>>, JsonSerializer<Multimap<String, ?>> {
    @Override public Multimap<String, ?> deserialize(JsonElement json, Type type,
            JsonDeserializationContext context) throws JsonParseException {
        final HashMultimap<String, Object> result = HashMultimap.create();
        final Map<String, Collection<?>> map = context.deserialize(json, multimapTypeToMapType(type));
        for (final Map.Entry<String, ?> e : map.entrySet()) {
            final Collection<?> value = (Collection<?>) e.getValue();
            result.putAll(e.getKey(), value);
        }
        return result;
    }

    @Override public JsonElement serialize(Multimap<String, ?> src, Type type, JsonSerializationContext context) {
        final Map<?, ?> map = src.asMap();
        return context.serialize(map);
    }

    private <V> Type multimapTypeToMapType(Type type) {
        final Type[] typeArguments = ((ParameterizedType) type).getActualTypeArguments();
        assert typeArguments.length == 2;
        @SuppressWarnings("unchecked")
        final TypeToken<Map<String, Collection<V>>> mapTypeToken = new TypeToken<Map<String, Collection<V>>>() {}
        .where(new TypeParameter<V>() {}, (TypeToken<V>) TypeToken.of(typeArguments[1]));
        return mapTypeToken.getType();
    }
}
Run Code Online (Sandbox Code Playgroud)

可在此处找到包含测试的完整代码.