I trying to serialize an "Iterable" from type Map.Entry with google GSON library - and i got an empty output.
here an example of the code:
static private Iterable<Map.Entry<String, Integer>> getIterable(){
HashMap<String, Integer> map = new HashMap<>();
map.put("1", 1);
map.put("2", 2);
Iterable<Map.Entry<String, Integer>> iterable = map.entrySet();
return iterable;
}
public static void main(String[] args) {
Iterable<Map.Entry<String, Integer>> myIterable = getIterable();
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.enableComplexMapKeySerialization().create();
String a= gson.toJson(myIterable);
System.out.println(a);
}
and this is the output :
[{},{}]
any idea what i am doing wrong?
thanks :)
java version: 1.8
gson version: 2.6.2
A cleaner approach might be
Or a
Streamversion, which I loveoutput:
[{"key":"1","value":1},{"key":"2","value":2}]TL;DR: you need a custom
TypeAdapterFactoryand a customTypeAdapter.See this method on
TypeAdaptersWithout a custom
TypeAdapterFactoryreturns
false, and even a customTypeAdapter<Entry>isn't used.The problem lies here, at
ReflectiveTypeAdapterFactory#writeand at
ReflectiveTypeAdapterFactory#getBoundFieldsGson is recognizing the input
Entry(Class<?> rawparameter) asTherefore
yield
true, and an emptyboundFieldsLinkedHashMapis returned.Thus, here
the loop isn't executed, and no values are extracted and written with