JodaTime的自定义反序列化器无法在Spring MVC中运行

时间:2014-05-06 10:04:44

标签: java json spring jackson

我正在尝试使用自定义Jackson序列化程序根据我想要的格式将Joda的DateTime对象转换为JSON。我不想注释每个实例,所以我想这样全局配置它:

 <bean id="jacksonMessageChanger" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes" value="application/json" />
        <property name="objectMapper" ref="jacksonObjectMapper" />
    </bean>

    <bean  id="jacksonObjectMapper" class="com.myapp.CustomJacksonObjectMapper" />

我的自定义映射器类:

public class CustomJacksonObjectMapper extends ObjectMapper {

    public CustomJacksonObjectMapper() {
        CustomSerializerFactory factory = new CustomSerializerFactory();
        factory.addSpecificMapping(DateTime.class, new DateTimeSerializer());
        this.setSerializerFactory(factory);
    }
}

最后我的序列化器:

public class DateTimeSerializer extends JsonSerializer<DateTime>{

    private static DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-yyyy");
    private static Logger logger = LoggerFactory.getLogger(DateTimeSerializer.class);

    @Override
    public void serialize(DateTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        String formattedDate = formatter.print(value);
        logger.debug("Converted date string: {}", formattedDate);
        jgen.writeString(formattedDate);
    }

}

但每次我尝试它都会得到一个无法反序列化的异常。我做错了什么?

0 个答案:

没有答案