I am using resteasy to send key/value pairs in between some restful web-services.
to post a list of these pairs i use this snippet
List<Pair> pairs = new ArrayList<>();
pairs.add(new Pair("name", "Arnold"));
pairs.add(new Pair("age", "20"));
ResteasyClient resteasyClient = getClient();
ResteasyWebTarget target = resteasyClient.target(targetURI);
Invocation.Builder request = target.request();
request.post(Entity.entity(entity, MediaType.APPLICATION_JSON_TYPE));
Pair
is just an unannotated Class with
public String key,
public String value
default constructor
(key,value) constructor
The target resource an receive this via:
@POST
@Path("/metadata")
@Consumes(MediaType.APPLICATION_JSON)
public Response postMetadata(List<Pair> properties) {...
the jax-rs resource can read the List correctly.
Now the other way is the Problem:
The Retrieval Resource is defined as:
@GET
@Path("/getUrl.../{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getMetadata(@PathParam("id") String id) {
data_from_hibernate = em.find(id);
...
List<Pair> properties = new ArrayList<>();
//fill List from data
return Response.ok().entity(properties).build();
Client side is:
Response response = request.get("http://getUrl.../"+id);
List<Pair> properties = response.readEntity(List.class);
logger.info("got properties != null? " +(properties!=null));
logger.info("size: "+properties.size());
logger.info("[0]" + properties.get(0));
logger.info("type: "+properties.get(0).getClass().getName());
The List is not null;
size is correct;
get(0) does output in a strange format: [0]{"name": "value"};
this is followed by the strange format's reason: an Exception tells me that:
java.util.LinkedHashMap cannot be cast to Pair
How is properties
a LinkedHashMap
at this point, or rather: a List of LinkedHashMaps?
Without type information (when you use readEntity
), Jackson (the underlying deserializer) will convert arbitrary JSON objects to LinkedHashMap
.
When using readEntity
, you provide generic type information by using GenericType
.
List<Pair> properties = response.readEntity(new GenericType<List<Pair>>(){});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With