How to use OpenFeign to get a pojo array?

2k Views Asked by At

I’m trying to use a OpenFeign client to hit an API, get some JSON, and convert it to a POJO array.

Previously I was simply getting a string of JSON and using Gson to convert it to the array like so

FeignInterface {
    String get(Request req);
}
String json = feignClient.get(request);
POJO[] pojoArray = new Gson().fromJson(json, POJO[].class);

This was working. I would like to eliminate the extra step and have feign auto decode the JSON and return a POJO directly though, so I am trying this

FeignInterface {
    POJO[] get(Request req);
}
POJO[] pojoArray = feignClient.getJsonPojo(request);`

I am running into this error

feign.codec.DecodeException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 2 path $

Both methods used the same builder

feignClient = Feign.builder()
     .encoder(new GsonEncoder())
     .decoder(new GsonDecoder())
     .target(FeignInterface.class, apiUrl);

Anyone have any ideas?

1

There are 1 best solutions below

0
Michał Ziober On BEST ANSWER

You have broken JSON payload. Before serialising you need to remove all unsupported characters. Feign allows this:

If you need to pre-process the response before give it to the Decoder, you can use the mapAndDecode builder method. An example use case is dealing with an API that only serves jsonp, you will maybe need to unwrap the jsonp before send it to the Json decoder of your choice:

public class Example {
  public static void main(String[] args) {
    JsonpApi jsonpApi = Feign.builder()
         .mapAndDecode((response, type) -> jsopUnwrap(response, type), new GsonDecoder())
         .target(FeignInterface.class, apiUrl);
  }
}

So, you need to do the same in your configuration and:

  • trim response and remove all whitespaces at the beginning and end of payload.
  • remove all new_line characters like: \r\n, \r, \n

Use online tool to be sure your JSON payload is valid and ready to be deserialised .