我在java中編寫了一些JSON解析代碼,我有幾個方法,它們之間的唯一區別是它們是否返回JSONObject
或JSONArray
。我想從這個去:創建模板類型的新對象,參數
private JSONArray getJsonArray(String path) throws IOException {
HttpGet httpget = new HttpGet(path);
httpget.setConfig(requestConfig);
try (CloseableHttpClient httpClient = httpClientBuilder.build()) {
try (CloseableHttpResponse result = httpClient.execute(apiHost, httpget)) {
return new JSONArray(new JSONTokener(result.getEntity().getContent()));
}
}
}
private JSONObject getJsonObject(String path) throws IOException {
HttpGet httpget = new HttpGet(path);
httpget.setConfig(requestConfig);
try (CloseableHttpClient httpClient = httpClientBuilder.build()) {
try (CloseableHttpResponse result = httpClient.execute(apiHost, httpget)) {
return new JSONObject(new JSONTokener(result.getEntity().getContent()));
}
}
}
這個(無效代碼):
private <T> get(String path, Class<T> type) throws IOException {
HttpGet httpget = new HttpGet(path);
httpget.setConfig(requestConfig);
try (CloseableHttpClient httpClient = httpClientBuilder.build()) {
try (CloseableHttpResponse result = httpClient.execute(apiHost, httpget)) {
return new T(new JSONTokener(result.getEntity().getContent()));
}
}
}
如何正確初始化類型T的帶參數的新對象?我能否以某種方式將T的可能值限制爲JSONObject/JSONArray?我知道的<T extends Something>
形式,但是這兩個似乎從Object
沒有共同的接口:(
'org.json'(我」假設你正在使用)不支持基因ric反序列化。使用更復雜的東西,如傑克遜或Gson。 –
@SotiriosDelimanolis我不認爲這是一個愚蠢的問題。另一個問題基本上是「如何解析JSON」,而這是「如何創建對應於泛型參數的類的實例」,它完全獨立於JSON。 –
@SotiriosDelimanolis提供的代碼只是爲了更好地說明我的觀點。 tobias_k得到了我的問題的本質。 –