2016-01-21 69 views
0

我正在試圖創建一個泛型方法來將JSON列表解包到包含POJO的列表中。下面的代碼片段編譯並運行,但是在運行時,我得到填充了HashMap實例的我的List<CustomPojo>,因爲類型T沒有傳遞給TypeReference構造函數,然後我回到HashMap將方法泛型傳遞給內部調用

public static <T> List<T> getList(String endpoint) throws IOException { 
    HttpGet request = new HttpGet(SERVER_ADDRESS + endpoint); 
    CloseableHttpResponse response = httpClient.execute(request); 
    try { 
     StatusLine statusLine = response.getStatusLine(); 
     if (statusLine.getStatusCode() == 200) { 
      return mapper.readValue(response.getEntity().getContent(), new TypeReference<List<T>>() { }); 
     } 
    } finally { 
     response.close(); 
    } 
    return null; 
} 

我在正確的軌道上,還是這是使用泛型不可實現的東西?

回答

1

嘗試使用類似:

mapper.readValue(response.getEntity().getContent(), 
    mapper.getTypeFactory().contructCollectionType(List.class, cls); 

其中clsClass<T>它應該工作。

+0

+1 Thanks @bodo,這實際上已經解決了這個問題,但我真的在詢問有關泛型的行爲(這就是爲什麼我沒有將Jackson添加到問題標題或標籤)。這也意味着添加類作爲附加的方法參數。 – zerga

+0

我不認爲這是可以通過使用泛型,這就是爲什麼我建議你解決上面發佈的解決方案。 – bodo