我在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得到了我的问题的本质。 –