使用澤西我喜歡定義一個服務:使用傑克遜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