Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap Jackson custom serializer / deserializer during runtime

I have the following system:

enter image description here

  • I am sending MediaType.APPLICATION_JSON_VALUEs from spring controllers to my client and vice versa.
  • I also have an export/import feature of my to-be-serialized classes. The JSON File is created by using an ObjectMapper and utilizing the writeValueAsString and readValue methods. I am reading from and writing into the json file.
  • Both of those serialization paths currently utilize the same serializers/deserializers.

I use the @JsonSerialize and @JsonDeserialize annotations to define custom serialization for some of my objects. I want to serialize those objects differently for export/import.

So I want to swap the serializer / deserializer for the export/import task. Something like this:

enter image description here

If I understand the docs correctly, those two annotations only allow one using class. But I want to register multiple serializers/deserializers and use them based on some conditional logic.

like image 957
Bishares Avatar asked Feb 12 '26 01:02

Bishares


1 Answers

You might want to have two separate ObjectMapper instances configured for Server and Client.

Server module:

ObjectMapper serverMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(ServerDTO.class, new CustomerFileSerializer());
module.addDeserializer(ServerDTO.class, new CustomerFileDeserializer());
serverMapper.registerModule(module);

ServerDTO serverDto = serverMapper.readValue(jsonInput, ServerDTO.class);
String serialized = serverMapper.writeValueAsString(serverDto);

and

Client module:

ObjectMapper clientMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(ClientDTO.class, new CustomerClientSerializer());
module.addDeserializer(ClientDTO.class, new CustomerClientDeserializer());
clientMapper.registerModule(module);

ClientDTO clientDTO = clientMapper.readValue(jsonInput, ClientDTO.class);
String serialized = clientMapper.writeValueAsString(clientDTO);
like image 149
Nikolai Shevchenko Avatar answered Feb 13 '26 17:02

Nikolai Shevchenko