Basically I have some Java objects that I want serialized to JSON with as little headache as possible. Right now I'm using Tomcat, Jersey and Genson.
I've discovered that something like this doesn't work (this is a toy example, of course) with Genson:
public class Main {
public static void main(String[] args) {
MyClass mc = new MyClass();
mc.mapOfSets = new HashMap<>();
Set<String> set0 = new HashSet<>();
set0.add("0");
Set<String> set1 = new HashSet<>();
set1.add("1");
set1.add("11");
Set<String> set2 = new HashSet<>();
set2.add("2");
set2.add("22");
set2.add("222");
mc.mapOfSets.put("set0", set0);
mc.mapOfSets.put("set1", set1);
mc.mapOfSets.put("set2", set2);
try {
String json1 = new Genson().serialize(mc.mapOfSets);
System.out.println(json1);
String json = new Genson().serialize(mc);
System.out.println(json);
} catch (TransformationException | IOException e) {
e.printStackTrace();
}
}
}
class MyClass {
public Map<String, Set<String>> mapOfSets;
}
The output of the above is this:
{"set1":["1","11"],"set0":["0"],"set2":["2","222","22"]}
{"mapOfSets":{"empty":false}}
What was nice about Genson is I just dropped it in my WebContent folder and it was used instead of whatever was bundled with Jersey - no additional configuration was necessary. If there's a really straight-forward approach to getting an object like the above to serialize to JSON without having to write some sort of converter for each schema, I'd gladly use that with Jersey instead of Genson, but Genson has not failed me thus far in shortcomings.
So - how do I massage Genson to serialize properly - or what is a library that handles this sort of thing painlessly?
Thanks!