How to use OpenFeign to get a pojo array?

孤街醉人 提交于 2019-12-13 02:17:11

问题


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:


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 .



来源:https://stackoverflow.com/questions/55012543/how-to-use-openfeign-to-get-a-pojo-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!