You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android开发求助:如何从JSON数据填充ListView?

How to Convert Parsed JSON to ArrayList for Your ListView Adapter

Hey there! Let's walk through exactly how to turn your parsed JSON data into an ArrayList<Book> so you can initialize your BookAdapter and populate that ListView.

First, Double-Check Your Model Classes

Since your JSON has a nested structure, your ResponseListModel needs to mirror that to properly parse the data. Here's how it should look (I'll use Gson-compatible structure since it's the most common Android JSON parsing library):

// ResponseListModel.java
public class ResponseListModel {
    private Library library;

    // Getter for library
    public Library getLibrary() {
        return library;
    }

    // Nested class for the outer "library" object
    public static class Library {
        private List<Book> books;
        private LibraryDetail library;

        // Getters
        public List<Book> getBooks() {
            return books;
        }

        public LibraryDetail getLibrary() {
            return library;
        }

        // Nested class for the inner "library" object with name
        public static class LibraryDetail {
            private String name;

            public String getName() {
                return name;
            }
        }
    }
}

And your Book class should match the book objects in the JSON:

// Book.java
public class Book {
    private String name;
    private String autor; // Match the JSON field name exactly!
    private String year;

    // Getters and setters (or use a constructor if you prefer)
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public String getAutor() { return autor; }
    public void setAutor(String autor) { this.autor = autor; }

    public String getYear() { return year; }
    public void setYear(String year) { this.year = year; }
}

Option 1: Use Gson for Parsing (Simpler)

If you're using Gson (add the dependency to your build.gradle if you haven't), here's how to implement the books() method:

// Inside MainActivity's void books() method
public void books() {
    // 1. Get your JSON string (from network, local file, etc.)
    String jsonString = "YOUR_JSON_DATA_HERE";

    // 2. Parse JSON to ResponseListModel
    Gson gson = new Gson();
    ResponseListModel responseModel = gson.fromJson(jsonString, ResponseListModel.class);

    // 3. Extract the list of books and convert to ArrayList
    List<Book> bookList = responseModel.getLibrary().getBooks();
    ArrayList<Book> books = new ArrayList<>(bookList);

    // 4. Initialize adapter and set to ListView
    BookAdapter adapter = new BookAdapter(this, books);
    yourListView.setAdapter(adapter); // Replace "yourListView" with your actual ListView ID
}

Option 2: Native JSON Parsing (No External Libraries)

If you don't want to use Gson, you can parse the JSON manually using Android's built-in JSONObject and JSONArray classes:

// Inside MainActivity's void books() method
public void books() {
    try {
        // 1. Get your JSON string
        String jsonString = "YOUR_JSON_DATA_HERE";

        // 2. Traverse the JSON structure
        JSONObject rootObject = new JSONObject(jsonString);
        JSONObject libraryObject = rootObject.getJSONObject("library");
        JSONArray booksArray = libraryObject.getJSONArray("books");

        // 3. Convert each JSON book to a Book object and add to ArrayList
        ArrayList<Book> books = new ArrayList<>();
        for (int i = 0; i < booksArray.length(); i++) {
            JSONObject bookJson = booksArray.getJSONObject(i);
            Book book = new Book();
            book.setName(bookJson.getString("name"));
            book.setAutor(bookJson.getString("autor"));
            book.setYear(bookJson.getString("year"));
            books.add(book);
        }

        // 4. Set up the adapter
        BookAdapter adapter = new BookAdapter(this, books);
        yourListView.setAdapter(adapter);
    } catch (JSONException e) {
        // Handle parsing errors (log the exception, show an error message, etc.)
        e.printStackTrace();
    }
}

Important Notes to Avoid Issues

  • Field Name Matching: Make sure your model class fields exactly match the keys in your JSON (e.g., "autor" not "author"). If you need to use different names in your code, use @SerializedName("autor") in your Book class (for Gson).
  • Async Operations: If you're fetching the JSON from a network call, make sure you run the adapter initialization on the main thread (use runOnUiThread() inside your async callback to avoid Android runtime errors).
  • List vs. ArrayList: Your BookAdapter takes a List<Book> parameter, so you don't strictly need to convert to ArrayList—you can pass the List<Book> directly. The conversion is only if you specifically need an ArrayList for other logic.

内容的提问来源于stack exchange,提问作者user10689078

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:42:49