Resteasy将列表转换为LinkedHashMap [英] Resteasy converting List to LinkedHashMap
问题描述
我正在使用resteasy在一些宁静的Web服务之间发送键/值对.
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
只是带有
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) {...
jax-rs资源可以正确读取列表.
the jax-rs resource can read the List correctly.
现在另一种方法是问题:
Now the other way is the Problem:
检索资源定义为:
@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();
客户端是:
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());
列表不为空;
大小正确;
get(0)确实以奇怪的格式输出:[0] {"name":"value"};
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无法强制转换为Pair
java.util.LinkedHashMap cannot be cast to Pair
此时properties
是LinkedHashMap
是什么,或者更确切地说是:LinkedHashMaps列表?
How is properties
a LinkedHashMap
at this point, or rather: a List of LinkedHashMaps?
推荐答案
在没有类型信息的情况下(当您使用readEntity
时),Jackson(底层反序列化器)会将任意JSON对象转换为LinkedHashMap
.
Without type information (when you use readEntity
), Jackson (the underlying deserializer) will convert arbitrary JSON objects to LinkedHashMap
.
使用readEntity
时,通过使用 GenericType
.
When using readEntity
, you provide generic type information by using GenericType
.
List<Pair> properties = response.readEntity(new GenericType<List<Pair>>(){});
这篇关于Resteasy将列表转换为LinkedHashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!