Spring Boot API响应返回不同的结构导致转换错误

b4wnujal  于 2023-03-02  发布在  Spring
关注(0)|答案(1)|浏览(143)

我从API返回了这个json响应:
结果是:

{
  "Result": {"name":"Jason"},
  "Status": 1
}

没有结果:

{
  "Result": "Not found",
  "Status": 1
}

正如你所看到的格式的不同.
当使用Feign时,没有找到我一定会击中转换错误:

@GetMapping(path = "/test", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseDto sendRequest(@RequestParam("id") String ID);
}

有什么方法可以在不改变API的情况下解决这个问题吗?我肯定会遇到错误

Cannot construct instance of `com.clients.dto.ResponseDto` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('Not found.')
lbsnaicq

lbsnaicq1#

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

public class ResponseDto<T>{

private T Result;
private Long Status;

...getters and setters....

}

也可以为其他类创建模型:

public class SuccessResult{

private String name;

...getters and setters....

}

现在假装:

@GetMapping(path = "/test", produces = MediaType.APPLICATION_JSON_VALUE)
    public <T> ResponseDto<T> sendRequest(@RequestParam("id") String ID);
}

或...

@GetMapping(path = "/test", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseDto<?> sendRequest(@RequestParam("id") String ID);
}

得到响应后,使用对象Map器转换值:

import com.fasterxml.jackson.databind.ObjectMapper;

.....

@Autowired
ObjectMapper objectMapper;

//....your method and logic...

ResponseDto responseDto = sendRequest("1");

String res = null;
String successResponse = null;

if(responseDto.getResult() instanceof String)
{
    res = objectMapper.convert(responseDto.getResult(), String.class);

} else{

    successResponse = objectMapper.convert(responseDto.getResult(), SuccessResult.class);

}

相关问题