简体   繁体   English

春天4,自定义messageConverter不起作用

[英]Spring 4 ,the custom messageConverter don`t work

I want to use @RestController annotation & jackson2, but the response JSON (include java.util.Date) always return Timestamp;I did the following things, but it dose not work... 我想使用@RestController注释和jackson2,但是响应JSON(包括java.util.Date)始终返回Timestamp;我做了以下事情,但是它不起作用...

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
        <bean id="customJsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper" ref="customObjectMapper"/>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>



public class CustomObjectMapper extends ObjectMapper{


public CustomObjectMapper(){
    this.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    this.setDateFormat(df);
}

} }

@RestController
@RequestMapping(value = "/reports")
public class ReportController extends...

debug and find there is only defualt 5 MessageConverters... the screenshoot 调试,发现只有defualt 5了MessageConverter ... 的screenshoot

This is how you could do it using annotations 这就是您可以使用注释来完成的方法

@Configuration
public class JacksonConfiguration extends WebMvcConfigurerAdapter {

    private final CustomObjectMapper mapper;

    @Autowired
    public JacksonConfiguration(CustomObjectMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new MappingJackson2HttpMessageConverter(mapper));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM