如何在Android Studio中从Assets文件夹加载JSON数据到RecyclerView
Alright, let's get your Assets folder JSON data displayed in a RecyclerView on Android Studio. I'll walk you through every step with your specific Bible JSON example, so you can follow along easily.
- First off, make sure your
assetsfolder lives underapp/src/main. If you don't have one yet, right-click onmain> New > Folder > Assets Folder to create it. - Drop your JSON file (let's name it
bible_data.json) inside. Your sample data looks like this:
{
"book": "Luke",
"chapters": [
{
"chapter": "1",
"verses": [
{
"1": "Forasmuch as many have taken in hand to set forth in order a declaration of those things which are most surely believed among us,"
}
]
}
]
}
We need to convert that JSON into usable Kotlin/Java objects. Let's go with Kotlin here (Java works similarly—just adjust the syntax):
First, a simple Verse class to hold each verse's number and text:
data class Verse(val verseNumber: String, val text: String)
Next, a Chapter class to group verses under a chapter number:
data class Chapter( val chapter: String, val verses: List<Verse> )
And a top-level Book class to wrap the whole structure:
data class Book( val book: String, val chapters: List<Chapter> )
Let's make a helper function to load the JSON file. You can put this directly in your Activity/Fragment or tuck it into a utility class:
private fun loadJSONFromAsset(): String? { return try { val inputStream = assets.open("bible_data.json") val size = inputStream.available() val buffer = ByteArray(size) inputStream.read(buffer) inputStream.close() String(buffer, Charsets.UTF_8) } catch (ex: IOException) { ex.printStackTrace() null } }
We'll use Gson for parsing—first add it to your module-level build.gradle file:
dependencies { implementation 'com.google.code.gson:gson:2.10.1' }
Sync your project once you add that.
Now, parse the JSON. Note that your verses use dynamic keys (like "1" for the verse number), so we'll handle that manually instead of relying on automatic parsing:
val jsonString = loadJSONFromAsset() ?: return // Bail if we couldn't load the file val gson = Gson() val bookJson = JsonParser.parseString(jsonString).asJsonObject // Extract book name val bookName = bookJson.get("book").asString // Parse chapters and verses val chaptersList = mutableListOf<Chapter>() val chaptersJson = bookJson.getAsJsonArray("chapters") for (chapterElement in chaptersJson) { val chapterObj = chapterElement.asJsonObject val chapterNumber = chapterObj.get("chapter").asString val versesList = mutableListOf<Verse>() val versesJson = chapterObj.getAsJsonArray("verses") for (verseElement in versesJson) { val verseObj = verseElement.asJsonObject // Grab the only key-value pair in the verse object (number + text) val verseEntry = verseObj.entrySet().first() versesList.add(Verse(verseEntry.key, verseEntry.value.asString)) } chaptersList.add(Chapter(chapterNumber, versesList)) } // Now we have our fully parsed Book object val book = Book(bookName, chaptersList)
First, add RecyclerView to your main activity layout (e.g., activity_main.xml):
<androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
Then create a list item layout (e.g., item_verse.xml) to display each verse:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="16dp"> <TextView android:id="@+id/tvChapterVerse" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:textSize="16sp"/> <TextView android:id="@+id/tvVerseText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:textSize="14sp"/> </LinearLayout>
This adapter will bind our verse data to the list items. For simplicity, we'll display all verses in a flat list (if you want expandable chapters, that's a bit more complex, but this gets you started):
class VersesAdapter( private val verses: List<Verse>, private val bookName: String ) : RecyclerView.Adapter<VersesAdapter.VerseViewHolder>() { inner class VerseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val tvChapterVerse: TextView = itemView.findViewById(R.id.tvChapterVerse) val tvVerseText: TextView = itemView.findViewById(R.id.tvVerseText) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VerseViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_verse, parent, false) return VerseViewHolder(view) } override fun onBindViewHolder(holder: VerseViewHolder, position: Int) { val verse = verses[position] // Show something like "Luke 1:1" for the verse label holder.tvChapterVerse.text = "$bookName ${verse.verseNumber}" holder.tvVerseText.text = verse.text } override fun getItemCount(): Int = verses.size }
In your Activity's onCreate method (or Fragment's onViewCreated):
val recyclerView = findViewById<RecyclerView>(R.id.recyclerView) // Collect all verses from all chapters into a single list val allVerses = book.chapters.flatMap { it.verses } val adapter = VersesAdapter(allVerses, book.book) recyclerView.adapter = adapter
- If your assets folder isn't showing up, double-check it's under
app/src/mainand namedassets(lowercase). - If parsing fails, validate your JSON with a tool like JSONLint to make sure it's properly formatted.
- Don't forget to sync your project after adding the Gson dependency!
内容的提问来源于stack exchange,提问作者Muloni Bryan

