i deserialize a widget-hierarchy using gson, but have problems deserializing final fields.
Example:
public final class Screen{
@Expose
private final List<WidgetDefinition> children = null;
@Expose
private final String name = null;
}
public final class AWidget implements WidgetDefinition {
@Expose
private final String name = null;
}
i’m deserializing a Screen using a custom deserializer for WidgetDefinition, shown below. ‘name’ in Screen is set correctly, ‘name’ in AWidget stays null.
final class Deserializer implements JsonDeserializer<WidgetDefinition> {
public WidgetDefinition deserialize(final JsonElement json, final Type type,
final JsonDeserializationContext context) {
JsonObject jsonObject = json.getAsJsonObject();
String typeName = jsonObject.get("type").getAsString();
if (typeName.equals("awidget")) {
return context.deserialize(json, AWidget.class);
} else {
return null;
}
}
}
Edit: I wonder if it has to do something with this:
Gson 1.7 won’t serialize subclass fields in collection elements. 2.0 adds this extra information.
Gson uses reflection to set final fields (via
.setAccessible(true)), so the problem you describe (and other related) probably comes from the way Java handles finals…