3

我有一个 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被序列化为其完全限定的类名。

我是否需要为此客户端设置自定义编码器/解码器组合?我该怎么做?

4

1 回答 1

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;
    }
}
于 2017-10-09T20:36:47.530 回答