eclipse 在微服务通信中使用RestTemplate和ResponseEntity时出现反序列化错误

cotxawn7  于 2023-05-17  发布在  Eclipse
关注(0)|答案(1)|浏览(110)

我正在实现两个微服务之间的通信,其中**微服务1使用RestTemplate向微服务2发送请求。在微服务1中,我在尝试使用ResponseEntity<Greeting>反序列化响应时遇到了一个问题。奇怪的是,它在使用ResponseEntity<Object>时工作正常。但是,我需要将响应作为Greeting类的示例,因此使用ResponseEntity<Object>实际上并没有什么用处。
我错过了什么?为了成功地将响应反序列化为Greeting对象,我需要做哪些不同的操作?

我收到以下错误信息:

There was an unexpected error (type=Internal Server Error, status=500).
Type definition error: [...Greeting]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: 
Cannot construct instance of `...Greeting` (no Creators, like default constructor, exist):
Cannot deserialize from Object value (no delegate- or property-based Creator) at [Source: (PushbackInputStream); line: 1, column: 2]
org.springframework.http.converter.HttpMessageConversionException:
Type definition error: [simple type, class ...Greeting];
nested exception is .fasterxml.jackson.databind.exc.InvalidDefinitionException:
Cannot construct instance of Greeting` (no Creators, like default constructor, exist):
cannot deserialize from Object value (no delegate- or property-based Creator)

微服务1(GreetingsController类)调用函数:

...
@Autowired
private RestTemplate restTemplate;

@Bean
public RestTemplate getRestTemplate() {
    return new RestTemplate();
}

@ResponseBody
public Greeting getGreeting() {
    ....
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> requestEntity = new HttpEntity<>(requestHeaders);
    // This one does not work
    //ResponseEntity<Greeting> response = restTemplate.exchange("http://localhost:8081/greetings", HttpMethod.GET, requestEntity, Greeting.class, "get");
    // only the following works
    ResponseEntity<Object> response = restTemplate.exchange("http://localhost:8081/greetings", HttpMethod.GET, requestEntity, Object.class, "get");
    ...
    return response.getBody(); 
}

下面是微服务1中的Greeting类:

// some imports here
@Data
@AllArgsConstructor
public class Greeting {
    @NotBlank
    private Integer id;
    @NonNull
    private String text;
}

我尝试了各种在线教程,并尝试了RestTemplate提供的不同方法,例如restTemplate.getForObject()restTemplate.getForEntity()restTemplate.exchange()。不幸的是,这些方法都没有与Greeting类结合使用。

xlpyo6sf

xlpyo6sf1#

试试这个应该能行

HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.APPLICATION_JSON);            
    HttpEntity<?> requestEntity=new HttpEntity<>(requestHeaders);             
    ParameterizedTypeReference<Greeting> responseType =  new ParameterizedTypeReference<Greeting>() {};    
    ResponseEntity<Greeting> responseEntity = restTemplate.exchange(yourUrl,HttpMethod.GET, requestEntity,responseType); 
    return response.getBody();

相关问题