Reputation: 11895
I've read a Jersey tutorial and it seems like its web client returns a response of type String, meaning I need to parse the response by myself.
Is there any library in Java (or third party) that can convert the response automatically from JSON to Java? It can make sense by using generics. e.g. let's say I expect the response body to be an array of Person, then I would do something like:
FooResponse response = FooRestClient.makeRequest<Person[]>("http://www.foo.com/api/people","GET");
Person[] people = response.status == 200 ? response.body : [];
If there's no way to do that (or similar), what's the easiest way to parse the response and then convert the response body to a Java object?
Upvotes: 0
Views: 1158
Reputation: 208994
I suggest you read Chapter 8 and 9 of Jersey docs. Chapter 8 is about entity providers and explains how conversion is done from different Java types. For example conversion from JSON to a POJO. Chapter 9 discusses some of the providers provided by Jersey, including those for JSON/XML to/from POJO conversion.
Once you have registered one of these entity providers, then you should be able to make the conversions you want, more that just Strings. For example if you add the jersey-media-json-jackson
provider, you can convert JSON to a POJO.
Response res = client.target(url).request().get();
MyPojo pojo = res.readEntity(MyPojo.class);
Upvotes: 1