如何从REST控制器端点返回LocalDateTime



我正在用Spring-java编写一个REST控制器,我的一个端点应该返回一个LocalDateTime变量

@GetMapping(path = "/lastDateTimeOfReset")
LocalDateTime fetchLastDateTimeOfReset() {
return mongoManagerService.fetchLastDateTimeOfReset();
}

这是客户端请求:

ResponseEntity<LocalDateTime> lastDateEntity = restTemplate.getForEntity(url, LocalDateTime.class);

我在我的客户方面获得了以下优势:

org.springframework.web.client.RestClientException: 
Error while extracting response for type [class java.time.LocalDateTime] and content type [application/json;charset=UTF-8]; 
nested exception is org.springframework.http.converter.HttpMessageNotReadableException: 
JSON parse error: Expected array or string.; 
nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Expected array or string.
at [Source: (PushbackInputStream); line: 1, column: 1]

我在调试模式下检查了返回值,它是一个有效的LocalDateTime。为什么会抛出此异常,以及如何克服它

您可以使用String来解决这个问题。

@GetMapping(path = "/lastDateTimeOfReset")
String fetchLastDateTimeOfReset() {
return (mongoManagerService.fetchLastDateTimeOfReset()).toString();
}

客户请求:

ResponseEntity<String> lastDateEntity = restTemplate.getForEntity(url, String.class);

您需要检查mongoManagerService.fetchLastDateTimeOfReset((的返回类型

或者使用以下示例代码测试您的应用程序

服务

@GetMapping(path = "/lastDateTimeOfReset")
LocalDateTime fetchLastDateTimeOfReset() {
return LocalDateTime.now();
}

客户端

RestTemplate rs = new RestTemplate();
ResponseEntity<LocalDateTime> lastDateEntity = rs.getForEntity(new URI("http://localhost:8089/lastDateTimeOfReset"), LocalDateTime.class);
System.out.println(lastDateEntity);

输出

<2002020-02-19T15:00:51.603220,[内容类型:"application/json;charset=UTF-8",传输编码:"chunked",日期:"Wed,19 Feb 2020 09:30:51 GMT"]>

问题解决了!一般来说,我应该把这个配置添加到我的应用程序中:

@Configuration
public class MvcConfig {    
@Configuration
@EnableWebMvc
public class MessageConvertersConfiguration implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new MappingJackson2HttpMessageConverter(objectMapper()));
}
@Bean
public ObjectMapper objectMapper() {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss");
SimpleModule localDateModule = new SimpleModule();
localDateModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeFormatter));
localDateModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeFormatter));
ObjectMapper mapper = new ObjectMapper();
mapper.registerModules(localDateModule);
return mapper;
}
}
}

*重要!!-在测试中,将其添加到您的休息模板中:*

restTemplate.setMessageConverters(Collections.singletonList(new MappingJackson2HttpMessageConverter(objectMapper())));

最新更新