Skip to content

Instantly share code, notes, and snippets.

@trung
Last active April 14, 2023 19:41
Show Gist options
  • Save trung/e00da09a1eb45b976fb261fda882a6e9 to your computer and use it in GitHub Desktop.
Save trung/e00da09a1eb45b976fb261fda882a6e9 to your computer and use it in GitHub Desktop.
Jackson Custom Serializer for Class extending HashMap

MyClass must be configured to use Shape.OBJECT in order for Jackson to:

  • Use ObjectSerializer instead of MapSerializer
  • Invoke MyClassBeanSerializerModifier.modifySerializer
objectMapper
    .configOverride(MyClass.class)
    .setFormat(JsonFormat.Value.forShape(Shape.OBJECT));

Register the serializer modifier:

SimpleModule m = new SimpleModule();
m.setSerializerModifier(new MyClassBeanSerializerModifier());

objectMapper.registerModule(m);
public class MyClass extends HashMap<String, Object> {
private String name;
// getter .. setter
}
public class MyClassBeanSerializerModifier extends BeanSerializerModifier {
@Override
public JsonSerializer<?> modifySerializer(
final SerializationConfig config,
final BeanDescription beanDesc,
final JsonSerializer<?> serializer) {
if (beanDesc.getBeanClass().equals(MyClass.class)) {
return new MyClassSerializer(MyClass.class, (JsonSerializer<Object>) serializer);
}
return super.modifySerializer(config, beanDesc, serializer);
}
}
public class MyClassSerializer extends StdSerializer<MyClass> {
private final JsonSerializer<Object> defaultSerializer;
public MyClassSerializer(Class<MyClass> t, JsonSerializer<Object> serializer) {
super(t);
this.defaultSerializer = serializer;
}
@Override
public void serialize(
final LedgerAccount value, final JsonGenerator gen, final SerializerProvider provider)
throws IOException {
gen.writeStartObject();
defaultSerializer.unwrappingSerializer(NameTransformer.NOP).serialize(value, gen, provider);
for (Entry<String, Object> entry : value.entrySet()) {
String key = entry.getKey();
Object v = entry.getValue();
gen.writeObjectField(key, v);
}
gen.writeEndObject();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment