ramzixp ramzixp - 5 months ago 7
Android Question

JSON Object GSON into list

I want to implement my old code when I was populating JSON array into listview but my current json haven't specified array, overall json is an array...

Can somebody tell me how to transform my code to use JSON like this?

https://api-v2.hearthis.at/categories/drumandbass/?page=15&count=2

Code to use gson, my old:

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;
}

Answer

Instead of doing this:

JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = new JSONArray("arrayname");

Just do this:

JSONArray parentArray = new JSONArray(finalJson);
Comments