如何在android中的json对象中获取值数组作为值

时间:2016-10-13 05:04:50

标签: android json xml

String finalData = "{"Books":[{"name":"Genesis","chapters1":["Chapter No:1","Chapter No:2","Chapter No:3","Chapter No:4","Chapter No:5","Chapter No:6","Chapter No:7","Chapter No:8","Chapter No:9","Chapter No:10"]}]};



private void ChaptersData(String finalData) {

        try {
            JSONObject mainchapter=new JSONObject(finalData);
            JSONArray chapterdata=mainchapter.getJSONArray("Books");
            chapterList=new String[chapterdata.length()];
             for (int j=0;j<=chapterdata.length();j++){
                 JSONObject chapInterData=(JSONObject) chapterdata.get(j);

                 String chapter=chapInterData.getString(0);

                 Log.e("Chapter", " "+chapter);
                 chapterList[j]=chapter;
             }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

现在我如何从json对象中获取章节

2 个答案:

答案 0 :(得分:0)

将此代码放入for循环中

JSONArray chap = chapInterData.getJSONArray("chapters1");
for(int k =0;k<chap.length();k++)
{
    String data=chap.getString(k);
    Log.e("data", " "+data);
}

在您想要的data

中插入array

答案 1 :(得分:0)

我使用 Google Gson 库更改了代码,该库更可靠,更易于用于json解析:

String finalData = "{\"Books\":[{\"name\":\"Genesis\",\"chapters\":[\"Chapter No:1\",\"Chapter No:2\",\"Chapter No:3\",\"Chapter No:4\",\"Chapter No:5\",\"Chapter No:6\",\"Chapter No:7\",\"Chapter No:8\",\"Chapter No:9\",\"Chapter No:10\"]}]}";

private void ChaptersData(String finalData) {
    Gson gson = new Gson();

    BookModel bookModel = gson.fromJson(finalData, BookModel.class);
    BookModel.Books[] books = bookModel.getBooks();

    for (BookModel.Books book : books) {
        String[] chapters = book.getChapters();
        for (String chapter : chapters) {
            Log.e("Chapter", " " + chapter);
        }
    }
}

class BookModel {
    private Books[] Books;

    public Books[] getBooks() {
        return Books;
    }

    class Books {
        private String name;

        private String[] chapters;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String[] getChapters() {
            return chapters;
        }

        public void setChapters(String[] chapters1) {
            this.chapters = chapters1;
        }
    }
}

将此添加到您的应用 build.gradle 依赖关键字:

  

编译com.google.code.gson:gson:2.7&#39;