Java SimpleModule-class And Method Code Example
Here is an example of using the SimpleModule class in the com.fasterxml.jackson.databind package in Java:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
public class Example {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule("MyModule");
mapper.registerModule(module);
// Add serializers and deserializers to the module
module.addSerializer(MyClass.class, new MyClassSerializer());
module.addDeserializer(MyClass.class, new MyClassDeserializer());
}
}
class MyClass {
//...
}
class MyClassSerializer extends JsonSerializer<MyClass> {
//...
}
class MyClassDeserializer extends JsonDeserializer<MyClass> {
//...
}
This example creates an instance of the ObjectMapper class, which is used to convert between Java objects and JSON. It also creates an instance of the SimpleModule class and registers it to the ObjectMapper. With this, you can use the SimpleModule to add custom serializers and deserializers for specific classes, in this case MyClass.
In this example, the addSerializer method is used to register a custom serializer for the MyClass class, and the addDeserializer method is used to register a custom deserializer for the MyClass class. This means that when serializing or deserializing an instance of MyClass, the custom serializer and deserializer will be used, instead of the default ones provided by the ObjectMapper.
You can also use SimpleModule to add custom TypeIdResolver, SubtypeResolver, AbstractTypeResolver etc.
With this example, you can see how you can use the SimpleModule to add custom serializers and deserializers for specific classes and use it with ObjectMapper.