在android中解析json嵌套数组

时间:2017-05-05 10:09:57

标签: java android arrays json

我想在android中解析嵌套的json数组。我不知道如何解析数组中的数组。
以下是我的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和track 以下是我的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;
    }
}}

3 个答案:

答案 0 :(得分:0)

请尝试以下代码:

 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");

                JSONArray song = c.getJSONArray("song");
                for(int k=0; k<song.length(); k++){
                    JSONObject songObject = song.getJSONObject(k);
                    String id_song = songObject.getString("id_song");
                     String track = songObject.getString("track");
                }

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

答案 1 :(得分:0)

试试这个:

在build.gradle compile com.google.code.gson:gson:2.7'

中添加此gradle

并在包中添加以下类

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Example {

    @SerializedName("album")
    @Expose
    private List<Album> album = null;

    public List<Album> getAlbum() {
        return album;
    }

    public void setAlbum(List<Album> album) {
        this.album = album;
    }

    public class Song {

        @SerializedName("id_song")
        @Expose
        private String idSong;
        @SerializedName("track")
        @Expose
        private String track;

        public String getIdSong() {
            return idSong;
        }

        public void setIdSong(String idSong) {
            this.idSong = idSong;
        }

        public String getTrack() {
            return track;
        }

        public void setTrack(String track) {
            this.track = track;
        }

    }
    public class Album {

        @SerializedName("id_album")
        @Expose
        private String idAlbum;
        @SerializedName("name_album")
        @Expose
        private String nameAlbum;
        @SerializedName("song")
        @Expose
        private List<Song> song = null;

        public String getIdAlbum() {
            return idAlbum;
        }

        public void setIdAlbum(String idAlbum) {
            this.idAlbum = idAlbum;
        }

        public String getNameAlbum() {
            return nameAlbum;
        }

        public void setNameAlbum(String nameAlbum) {
            this.nameAlbum = nameAlbum;
        }

        public List<Song> getSong() {
            return song;
        }

        public void setSong(List<Song> song) {
            this.song = song;
        }

    }
}

然后使用

Example example = new Gson().fromJson(jsonStr,Example.class);
List<Album> albums = example.getAlbum();
List<Song> songs = albums.get(0).getSong();

并使用this链接创建pojo,并在此网址中选择JSON和GSON选项

答案 2 :(得分:0)

1)您应该格式化您的Json以获得更好的可读性,例如与http://www.jsoneditoronline.org比你得到

{
  "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"
        }
      ]
    }
  ]
}

2)您可以使用此插件https://plugins.jetbrains.com/plugin/7654-gsonformat

创建POJO

3)使用RetrofitMoshi下载您的数据