Convert Guava HashMultimap to json

sat picture sat · Sep 4, 2014 · Viewed 8.3k times · Source

I want to print HashMultiMap as json.

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

to

{ 
  "a":[Obj1,Obj3],
  "b":[Obj2]
}

Obj1 and other objects should again be in json(to keep it clean, I have shown it as objects)
I can iterate over the individual keys and convert set of Objects to json using libraries such as Gson.

But to get the entire snapshot of the HashMultimap, I want to convert it to json and inspect it.

Gson could not convert the entire map, but could do individual values(list of objects to json)

Answer

Wesley picture Wesley · Sep 5, 2014

Call asMap() on the MultiMap first. This converts the MultiMap to a standard Map where each value is a Collection.

In your example, the type of the resulting Map is Map<String, Collection<Object>>. Gson should be able to serialise this correctly.