1

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.

1 Answer 1

1

The issue is field.getType(), you should change it to field.getGenericType().

o.add(field.getName(), context.serialize(fieldValue, field.getGenericType()));

If you print both values to the console, the .getType() returns just a java.util.Map, but the .getGenericType() returns the actual type of your map Map<String, Map<String, Integer>>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.