使用泽西我喜欢定义一个服务:使用杰克逊ObjectMapper与泛型的POJO代替LinkedHashMap的
@Path("/studentIds")
public void writeList(JsonArray<Long> studentIds){
//iterate over studentIds and save them
}
其中JsonArray是:
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);
}
}
}
这一切正常,但是当我做更复杂的东西:
@Path("/studentIds")
public void writeList(JsonArray<TypeIdentifier> studentIds){
//iterate over studentIds and save them by type
}
凡Bean是一个简单的POJO如
public class TypeIdentifier {
private String type;
private Long id;
//getters/setters
}
整件事发生了可怕的事情。它将一切转换为LinkedHashMap而不是实际的对象。我可以得到它的工作,如果我手动创建类如:
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);
}
}
}
但我试图保持这个很好,通用,而无需添加额外的类遍及。任何线索为什么只有通用版本发生这种情况?
查看可能与接受的答案重复:http://stackoverflow.com/questions/6062011/jackson-is-not-deserialising-a-generic-list-that-it-has-serialised – 2013-04-14 15:23:16