问题描述
使用Jersey我正在定义一项服务:
Using Jersey I'm defining a service like:
@Path("/studentIds")
public void writeList(JsonArray<Long> studentIds){
//iterate over studentIds and save them
}
其中JsonArray是:
Where JsonArray is:
public class JsonArray<T> extends ArrayList<T> {
public JsonArray(String v) throws IOException {
ObjectMapper objectMapper = new ObjectMapper(new MappingJsonFactory());
TypeReference<ArrayList<T>> typeRef = new TypeReference<ArrayList<T>>() {};
ArrayList<T> list = objectMapper.readValue(v, typeRef);
for (T x : list) {
this.add((T) x);
}
}
}
这很好用,但是当我做一些更复杂的事情时:
This works just fine, but when I do something more complicated:
@Path("/studentIds")
public void writeList(JsonArray<TypeIdentifier> studentIds){
//iterate over studentIds and save them by type
}
Bean是一个简单的POJO,例如
Where the Bean is a simple POJO such as
public class TypeIdentifier {
private String type;
private Long id;
//getters/setters
}
整个事情突然爆发。它将所有内容转换为LinkedHashMap而不是实际对象。如果我手动创建一个类,我可以使它工作:
The whole thing breaks horribly. It converts everything to LinkedHashMap instead of the actual object. I can get it to work if I manually create a class like:
public class JsonArrayTypeIdentifier extends ArrayList<TypeIdentifier> {
public JsonArrayTypeIdentifier(String v) throws IOException {
ObjectMapper objectMapper = new ObjectMapper(new MappingJsonFactory());
TypeReference<ArrayList<TypeIdentifier>> typeRef = new TypeReference<ArrayList<TypeIdentifier>>(){};
ArrayList<TypeIdentifier> list = objectMapper.readValue(v, typeRef);
for(TypeIdentifier x : list){
this.add((TypeIdentifier) x);
}
}
}
但我正在尝试保持这个漂亮和通用,而不是添加额外的类。有没有为什么只发生通用版本?
But I'm trying to keep this nice and generic without adding extra classes all over. Any leads on why this is happening with the generic version only?
推荐答案
首先,它适用于Longs因为那是排序本机类型,以及JSON整数的默认绑定。
First of all, it works with Longs because that is sort of native type, and as such default binding for JSON integral numbers.
但是为什么泛型类型信息没有正确传递:这很可能是由于方式JAX-RS API将类型传递给 MessageBodyReader
s和 MessageBodyWriter
s - 传递 java。 lang.reflect.Type
不足以(不幸!)足以传递实际的通用声明(有关此内容的更多信息,请阅读)。
But as to why generic type information is not properly passed: this is most likely due to problems with the way JAX-RS API passes type to MessageBodyReader
s and MessageBodyWriter
s -- passing java.lang.reflect.Type
is not (unfortunately!) enough to pass actual generic declarations (for more info on this, read this blog entry).
一个简单的解决方法是创建辅助类型,如:
One easy work-around is to create helper types like:
class MyTypeIdentifierArray extends JsonArray<TypeIdentifier> { }
并使用该类型 - 事物将正常工作,因为超类型通用信息始终保留。
and use that type -- things will "just work", since super-type generic information is always retained.
这篇关于将Jackson ObjectMapper与泛型一起使用到POJO而不是LinkedHashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!