Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You want Jackson to always use your custom JsonSerializer or JsonDeserializer to serialize/deserialize a specific type?</p> <p>I ended up writing a custom Jackson module to let Jackson find serializers and deserializers that are Spring beans. I am using Spring 3.1.2 and Jackson 2.0.6</p> <p>Simplified version:</p> <pre><code>public class MyObjectMapper extends ObjectMapper { @Autowired public MyObjectMapper(ApplicationContext applicationContext) { SpringComponentModule sm = new SpringComponentModule(applicationContext); registerModule(sm); } } </code></pre> <p>Module: </p> <pre><code>public class SpringComponentModule extends Module { private ApplicationContext applicationContext; public SpringComponentModule(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Override public String getModuleName() { return "jackson-spring-component"; } @Override public Version version() { return SpringComponentModuleVersion.instance.version(); } @Override public void setupModule(SetupContext context) { context.addSerializers(new SpringComponentSerializers(this.applicationContext)); context.addDeserializers(new SpringComponentDeserializers(this.applicationContext)); } } </code></pre> <p>ComponentSerializer class:</p> <pre><code>public class SpringComponentSerializers extends Serializers.Base { private ApplicationContext applicationContext; public SpringComponentSerializers(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Override public JsonSerializer&lt;?&gt; findSerializer(SerializationConfig config, JavaType type, BeanDescription beanDesc) { Class&lt;?&gt; raw = type.getRawClass(); Map&lt;String,JsonSerializer&gt; beanSet = applicationContext.getBeansOfType(JsonSerializer.class); for(String beanName : beanSet.keySet()) { JsonSerializer&lt;?&gt; serializer = beanSet.get(beanName); if(serializer.handledType().isAssignableFrom(raw)) { return serializer; } } return null; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload