我想在android中解析嵌套的json數組。我不知道如何解析數組中的數組。
下面是我的JSON代碼
在android中解析json嵌套數組
{
"album": [{
"id_album": "svt001",
"name_album": "first album",
"song": [{
"id_song": "svt0000001",
"track": "1"
}, {
"id_song": "svt0000002",
"track": "2"
}]
}, {
"id_album": "svt002",
"name_album": "second album",
"song": [{
"id_song": "svt0000003",
"track": "1"
}, {
"id_song": "svt0000004",
"track": "2"
}, {
"id_song": "svt0000005",
"track": "3"
}]
}]}
我可以分析id_album和name_album,但我不知道怎麼去id_song和跟蹤
下面是我Album.java
public class Album extends AppCompatActivity{
private String TAG = Album.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> albumList;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.album);
albumList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetAlbums().execute();
}
private class GetAlbums extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(Album.this, "Album data is downloading",
Toast.LENGTH_LONG).show();
}
@Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
String url = "http://lyric.noviaprims.tk/json/listalbum.php";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray album = jsonObj.getJSONArray("album");
for (int i = 0; i < album.length(); i++) {
JSONObject c = song.getJSONObject(i);
String id_album = c.getString("id_album");
String name_album = c.getString("name_album");
HashMap<String, String> albums = new HashMap<>();
albums.put("id_album", id_album);
albums.put("name_album", name_album);
albumList.add(albums);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get song from server");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get album from server. Check logcat for possible errors",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
}}