I'm trying to create custom JsonSerializer for a class (and it's children).
So I'm iterating through the Fields of the class and doing stuff.
I faced with problem: If I have something like this in my class:
public Map<String, Map<String, Integer>> nestedHashMap = new HashMap<String, Map<String, Integer>>() {{
put("levelOneKey", new HashMap<String, Integer>() {{
put("levelTwoKey", 25);
}});
}};
It turns into {}. I checked, it has elements on creation, GSON just can't handle it properly. If I'll try to use GSON without JsonSerializer, it works.
Clearly, I'm doing something wrong. I don't have much experience with Java Reflection.
Part of my code:
@Override
public JsonElement serialize(JsonConfig src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject o = new JsonObject();
//...
Field[] fields = src.getClass().getDeclaredFields();
for (Field field : fields) {
Object fieldValue = null;
try {
fieldValue = field.get(src);
} catch (IllegalAccessException e) {
System.out.print("IllegalAccessException for field " + field.getName() + ": " + e.toString());
continue;
}
o.add(field.getName(), context.serialize(fieldValue, field.getType()));
}
//...
}
I tried to create another instance of Gson and replace o.add with:
o.add(field.getName(), gson.toJson(fieldValue, field.getType()));
I checked, fieldValue has elements.