Custom Serialization for all instances of Map<String, Object> using Jackson

19 views Asked by At

I wrote a custom serialization class that I want to apply for all Map<String, Object> instances in my immediate and child classes.

CustomSer.java

public class CustomSer extends StdSerializer<Map<String, Object>> {
  public CustomSer() {this(null)}

  public CustomSer(Class <Map<String, Object>> vc) {super(vc)}

  #Override
  public void serialize(Map<String, Object> map, JsonGenerator jG, SerializerProvider sP) throws IOException {
    ...
    for (Map.Entry<String, Object> entry : map.entrySet()) {
      jG.writeStringField(entry.getKey(), FuncToSerializeObjectIntoBytesAndEncodeToBase64(entry.getValue))
    }
  }
}

Usage for serialization

Map<String, Object> = HashMap()>
SimpleModule module = new SimpleModule()
module.addSerializer( (Class<Map<String, Object>>) mapClass.getClass(), new CustomSer());
object_mapper.registerModule(module)

...
// to serialize
object_mapper.writeValueAsBytes(data)

It seems like the addSerializer does not apply the CustomSer to all instances as I am still getting error related to Object and I haven't used Object in anywhere other than Map<String, Object>.

InvalidDefinitionException: No serializer found for class java.lang.Object and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ....... RegularImmutableMap["object"])

How can I ensure that my CustomSer is applied for all Map<String, Object> instances and therefore prevent independent serialization of Object class.

0

There are 0 answers