Search code examples
spring-bootgsonmicroservicesfeign

How to handle Feign Client response as JSONObject


Service A returning response as gson.JsonObject. From Service B calling Service A with Feign Client. How to handle response? Tried below:

@FeignClient(name = "ABC")
public interface TestDataProviderApi {
   @GetMapping(value = "/v1/path/{data-type}", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
    **JsonObject** getData(@PathVariable("data-type") String dataType);
}

@FeignClient(name = "ABC")
public interface TestDataProviderApi {
   @GetMapping(value = "/v1/path/{data-type}", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
    **Object** getData(@PathVariable("data-type") String dataType);
}

@FeignClient(name = "ABC")
public interface TestDataProviderApi {
   @GetMapping(value = "/v1/path/{data-type}", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
    **JSONObject** getData(@PathVariable("data-type") String dataType);
}

Nothing worked. Either response is printed as {} or JSON exceptions. But at Service A logs states it returned proper JSON like {"a":1}. How to handle the value? The end goal is to read responses from feign client and get value using Jayway JsonPath.

Thanks in Advance!


Solution

  • Spring boot using jackson serialization-de-serialization by default. As object returned is of type gson, adding below property worked to receive proper response with type: JsonObject.

    spring.http.converters.preferred-json-mapper=gson
    

    But this affected other controller and client behaviors as everything started expecting gson objects (not able to de-serialize JSONObjects).

    Instead, at feign client marking return type as Object and in service layer used type conversion with Gson() helped.