How to convert JSON to list of POJOs using RestEas

2020-04-22 10:33发布

问题:

I have to integrate our j2ee application with a REST webservice. And I wanted to use the RestEasy JAX-RS implementation from JBoss. The webservice returns an array in JSON format. I've this piece of code:

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://myservices.com/schemes/all");
Response response = target.request().get();

Can I map this "response" object to List<Scheme> using RestEasy? Thanks

回答1:

Provided that your JSON provider is capable of converting JSON to appropriate entities, then yes. The get method you call in the code has an overloaded version which accepts the class of entity to which the result is to be converted. Since there are problems with serializing certain collections' implementations, your type has to be wrapped in GenericType class, like that:

List<Scheme> schema = [...].get(new GenericType<List<Scheme>>(){});

The above method should work with just about every JAX-RS-compliant implementation.

You can also use Jackson library, which allows you (amongst other things) to pass collections without need of wrapping them.