Kong / unirest-java

Unirest in Java: Simplified, lightweight HTTP client library.
http://kong.github.io/unirest-java/
MIT License
2.59k stars 593 forks source link

get list of Objects #386

Closed idan72 closed 3 years ago

idan72 commented 3 years ago

Hi,

I have the following method which works OK: public Object sendRestGet(String url, Class<?> responseClass) throws UnirestException { return Unirest.get(url).asObject(responseClass).getBody(); }

Now I want to return List of objects(Different type of objects).

How do I add support that I can get as parameter List of any type of object ? I try using GenericType but I was able only if I specify specific class, How can I make it general ?

Thanks

ryber commented 3 years ago

There are several problems with what you want to do. Something has to tell the object mapper what the type is of the object to return, the only fallback you have is a List<Object> in which case the Mapper will end up giving you a list of LinkedHashMaps (the default Gson behavior).

vanilla Json doesn't have a way to transmit the type of the object. So how would the ObjectMapper know what it should return? There are in fact ways to express types in Json but they aren't common and require the server end to transmit @type fields and a schema. Unirest also doesn't have this feature enabled by default so you would have to supply your own ObjectMapper (the Jackson object mapper is better at this, but know that there are security risks associated with it as a server could send a @type for a server class that you would not want constructed)

Your better bet would be to deal with such an array as Json itself, and not an Object.

ryber commented 3 years ago

I'm going to go ahead and close this, feel free to follow up in the new github discussions if you want to chat more. https://github.com/Kong/unirest-java/discussions