Thursday, February 4, 2016

Mapping a list with no root element using Jersey and Moxy

Consider this piece of JSon code. To map this into a List of Strings is not always as easy it one might think.

 [  
   "ListElement1",  
   "ListElement2",  
   "ListElement3"  
 ]  
If you just do like below:
 ClientConfig clientConfig = new ClientConfig();  
 Client client = ClientBuilder.newClient(clientConfig);  
 WebTarget webTarget = client.target("http://localhost/service");  
 Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);  
    
 Response response = invocationBuilder.get();  
 List<String> owners = response.readEntity(ArrayList.class);  
You will get an error like this:
 org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyReader not found for media type=application/json, type=class java.util.ArrayList, genericType=class java.util.ArrayList.  
To solve the problem, use a GenericType.
 ClientConfig clientConfig = new ClientConfig();  
 Client client = ClientBuilder.newClient(clientConfig);  
 WebTarget webTarget = client.target("http://localhost/service");  
 Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);  
   
 Response response = invocationBuilder.get();  
 List<String> owners = response.readEntity(new GenericType<List<String>>() { });  
This should do the trick. It will work for Map's as well.

No comments:

Post a Comment