FeignClient:将RequestParam序列化为JSON

时间:2017-02-24 12:25:45

标签: spring-boot jackson feign

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

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

1 个答案:

答案 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;
    }
}