0

如果您需要一个类型的多个解串器(打包在一个或多个模块中),Jackson 如何确定哪个是该类型的主要解串器?是随机的吗?如果不是,可以通过包/类设置默认值吗?

显然,需要@JsonDeserialize(using=CustomDeserializer.class)为每个 Jackson 类指定具有给定类型的几乎每个属性是完全疯狂的——所以我假设当存在多个反序列化器时有一种方法可以设置默认值,但到目前为止还没有发现。

4

1 回答 1

1

好的,我回去看看我过去是如何做到的。同样,我使用的是 Spring。就我而言,我想从所有输入中删除前导和尾随空格。这就是我的做法。

在 spring xml 配置中,我有

<!-- 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"/>

这是 CustomObjectMapper 类

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

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

最后是 StringMapperModule 类

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());
            }
        });
    }
}

我希望这对您有所帮助,或者至少可以为您指明正确的方向。

于 2015-11-20T22:15:16.140 回答