0

If you need multiple deserializers for a type (packaged in one or more modules), how does Jackson determine which is the primary deserializer for that type? Is it random? If not, can the default be set by package/class?

It would obviously be a completely insane to need to specify @JsonDeserialize(using=CustomDeserializer.class) on almost every single property with a given type for each Jackson class -so I am assuming there is a method to set defaults when multiple deserializers exist, but have found nothing thus far.

THX1138
  • 1,518
  • 14
  • 28
  • I believe it is possible. I was using Spring and was able to access the ObjectMapper to override to default, but it has been a while since I have looked at that code. Are you using Spring? – Nick Allen Nov 20 '15 at 21:39

1 Answers1

1

Ok, I went back and looked at how I did this in the past. Again, I was using Spring. For my case, I wanted to trim off the leading and trailing whitespace from all my inputs. Here's how I did it.

In the spring xml config, I have

<!-- Configures the @Controller model -->
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager">
  <mvc:message-converters>
    <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
      <property name="prefixJson" value="false"/>
      <property name="supportedMediaTypes" value="application/json"/>
      <property name="objectMapper" ref="customObjectMapper"></property>
    </bean>
  </mvc:message-converters>
</mvc:annotation-driven>
<bean id="customObjectMapper" class="com.domain.json.CustomObjectMapper"/>

Here's the CustomObjectMapper class

public class CustomObjectMapper extends ObjectMapper
{
    private static final long serialVersionUID = 1L;

    public CustomObjectMapper()
    {
        registerModule(new StringMapperModule());
    }
}

And finally the StringMapperModule class

public class StringMapperModule extends SimpleModule
{
    private static final long serialVersionUID = 1L;

    /**
     * Modify json data globally
     */
    public StringMapperModule()
    {
         super();

        addDeserializer(String.class, new StdScalarDeserializer<String>(String.class)
        {
            private static final long serialVersionUID = 1L;

            @Override
            public String deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException
            {
                // remove leading and trailing whitespace
                return StringUtils.trim(jp.getValueAsString());
            }
        });
    }
}

I hope you find this helpful or that it at leasts points you in the right direction.

Nick Allen
  • 917
  • 11
  • 24