【发布时间】:2016-01-11 17:31:31
【问题描述】:
这有点令人沮丧...我以前的项目中有这个工作,但在调试几个小时后无法让它在我的新项目中工作。
假设我有一个简单的 Rest 控制器,它返回 Joda 的 LocalDate:-
@RestController
@RequestMapping(value = "/api")
public final class ApiController {
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<LocalDate> main() {
return new ResponseEntity<LocalDate>(LocalDate.now(), HttpStatus.OK);
}
}
默认情况下,当我调用http://app/api 时,我会得到[2015,10,13]。我真正想要的是2015-10-13。
为了在我之前的项目中解决这个问题,我在spring-servlet.xml 中使用了这个配置:-
<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
<context:component-scan base-package="test.controller"/>
<mvc:annotation-driven/>
<mvc:resources location="/resources/" mapping="/resources/**"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="objectMapper"
class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
p:indentOutput="true"
p:simpleDateFormat="yyyy-MM-dd'T'HH:mm:ss.SSSZ">
</bean>
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"
p:targetObject-ref="objectMapper"
p:targetMethod="registerModule">
<property name="arguments">
<list>
<bean class="com.fasterxml.jackson.datatype.joda.JodaModule"/>
</list>
</property>
</bean>
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="objectMapper"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
</beans>
但是,当我在我的新项目中做同样的事情时,我又得到了[2015,10,13] 而不是2015-10-13。
我确实升级了一些依赖项,并且我还确保没有额外的 ObjectMapper 被加载。
这是我当前的依赖树...我删除了所有我不需要的东西:-
如何配置 Spring MVC 以在 JSON 中返回正确的日期格式?
非常感谢。
【问题讨论】:
标签: java spring spring-mvc jackson jodatime