简体   繁体   English

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

[英]How to return LocalDateTime from REST controller endpoint?

I'm writing a REST controller in Spring- java, and one of my endpoints should return a LocalDateTime variable.我正在 Spring-java 中编写一个 REST 控制器,我的端点之一应该返回一个LocalDateTime变量。

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

This is the client request:这是客户端请求:

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

I get the following excepation on my client side:我的客户端出现以下异常:

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]

I checked the return value on debug mode and it is a valid LocalDateTime.我检查了调试模式下的返回值,它是一个有效的 LocalDateTime。 Why is this exception thrown and how to overcome it?为什么会抛出这个异常以及如何克服它?

You can use String to overcome this issue.您可以使用 String 来解决这个问题。

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

Client Request:客户要求:

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

You need to check return type of mongoManagerService.fetchLastDateTimeOfReset();您需要检查mongoManagerService.fetchLastDateTimeOfReset(); 的返回类型

Or Test your application with below sample code或使用以下示例代码测试您的应用程序

Service服务

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

Client客户

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

Output输出

<200,2020-02-19T15:00:51.603220,[Content-Type:"application/json;charset=UTF-8", Transfer-Encoding:"chunked", Date:"Wed, 19 Feb 2020 09:30:51 GMT"]> <200,2020-02-19T15:00:51.603220,[Content-Type:"application/json;charset=UTF-8", Transfer-Encoding:"chunked", Date:"Wed, 19 Feb 2020 09:30:格林威治标准时间 51"]>

Problem solved!问题解决了! In general- I should've added this configuration to my app:一般来说 - 我应该将此配置添加到我的应用程序中:

@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;
        }
    }
}

* IMPORTANT!!! * 重要的!!! - In Tests add this to your rest template: * - 在测试中将此添加到您的休息模板:*

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

暂无
暂无

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

相关问题 如何从 FeignClient 端点返回 LocalDateTime? - How to return LocalDateTime from FeignClient endpoint? 如何在返回类型为 LocalDateTime 的方法中从 LocalDateTime 对象中获取第二个? - How to get the second from LocalDateTime objects in a method with return type LocalDateTime? 如何使用java8 api(LocalDateTime)将本地日期时间从jsp传递到控制器? - How to pass LocalDateTime from jsp to controller using java8 api(LocalDateTime)? 我如何使用 REST controller GET 将 LocalDateTime 反序列化为 LocalDate,其中响应值为 LocalDateTime,DTO 中的值为 LocalDate? - How i can deserialize LocalDateTime into LocalDate using a REST controller GET where value in response is LocalDateTime, value in DTO is LocalDate? Rest controller 中的端点过载 - Endpoint overloading in Rest controller 在单元测试REST端点时,LocalDateTime被截断发送 - While unit testing REST endpoint, LocalDateTime is sent truncated How to pass JSON Object and return Object from Spring rest controller - How to pass JSON Object and return Object from Spring rest controller 从同一控制器的另一个REST端点直接调用REST端点(方法)是一种好习惯吗? - Is it good practice to directly call REST endpoint (method) from another REST endpoint of same controller? 如何测试REST控制器端点返回的JSON响应 - How to test json response returned by rest controller endpoint 如何从REST ENDPOINT解析JSON对象? - How to Parse JSON object from a REST ENDPOINT?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM