I'm trying to convert a Java Map (with a List of MyClass values) to json using gson.
Map<Integer, List<MyClass>> myMap
Here is how I am doing it...
Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
String json = gson.toJson(myMap);
System.out.println(json);
It produces json that is close to, but not in the format I would expect/want. Here is what is produced:
{"0":[{MyClassItem1}, {MyClassItem2}, etc], "1":[{MyClassItem3}, {MyClassItem4}, etc], etc... }
I would expect/prefer it produces:
[{"0":[{MyClassItem1}, {MyClassItem2}, etc]}, {"1":[{MyClassItem3}, {MyClassItem4}, etc]}, etc...]
Is this possible? If so, how?
Well... Gson serializes data to its most appropriate form. It seems that you want an array of Map.Entry
. Try something like:
Map<Integer, List<MyClass>> myMap = ...;
Set<Map.Entry<Integer, List<MyClass>>> entrySet = myMap.entrySet();
Object[] data = entrySet.toArray(new Object[entrySet.size()]);
// serialize data variable
However be aware that Gson might not be able to serialize Map.Entry
out-of-the-box.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.