我有一个spring boot应用程序,我试图使用Feign
与远程服务进行通信。我的@FeignClient
定义如下:
@FeignClient(name="TEST_SERVICE", url="URL")
@Component
public interface SomeServiceClient
{
@RequestMapping(
method = RequestMethod.POST,
value = "/someService",
consumes = "application/json",
produces = "application/json"
)
SomeServiceResult getServiceResult(
@RequestParam(value = "mode") String mode,
@RequestParam(value = "payload") SomeServicePayload payload
);
}
我希望将payload
类型的SomeServicePayload
对象序列化为JSON。我希望这会自动发生,但事实并非如此。相反,payload
被序列化为其完全限定的类名。
我是否需要为此客户端设置自定义编码器/解码器组合?我该怎么做?
答案 0 :(得分:0)
@FeignClient
使用toString()
方法来构建请求字符串。创建正确请求的最简单方法是手动覆盖toString()
方法:
class SomeServicePayload{
String payload;
@Override
public String toString() {
return "{\"payload\":\"" + payload + "\"}";
}
}
或者对于使用ObjectMapper的复杂对象:
public class SomeServicePayload{
private String payload;
public String getPayload() {
return payload;
}
public void setPayload(String payload) {
this.payload = payload;
}
private ObjectMapper mapper = new ObjectMapper();
@Override
public String toString() {
try {
return mapper.writeValueAsString(this);
} catch (JsonProcessingException e) {
//...
}
return null;
}
}