我想實現當我填充JSON數組列表視圖我的舊代碼,但我目前的JSON沒有指定數組,整體JSON是一個數組...JSON對象GSON到列表
有人可以告訴我如何將我的代碼轉換爲像這樣使用JSON?
https://api-v2.hearthis.at/categories/drumandbass/?page=15&count=2
代碼使用GSON,我的老:
protected List<Model> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = new JSONArray("arrayname");
List<Model> dataModelList = new ArrayList<>();
Gson gson = new Gson();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
Model modelList = gson.fromJson(finalObject.toString(), Model.class);
dataModelList.add(modelList);
}
return dataModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
我你,但THX之前想通了,答案接受,因爲它是100%正確的 – ramzixp