如何从资源目录上的JSON文件中读取数据?我需要读取资源目录上的json文件,将其转换为数据类("User"),我正在尝试修改以下代码
private fun getJSONFromAssets(): String? {
var json: String? = null
val charset: Charset = Charsets.UTF_8
try {
val myUsersJsonFile = assets.open("users.json")
val size = myUsersJsonFile.available()
val buffer = ByteArray(size)
myUsersJsonFile.read(buffer)
myUsersJsonFile.close()
json = String(buffer, charset)
} catch (ex: IOException) {
ex.printStackTrace()
return null
}
return json
}但assets.open("users.json")未被识别。在资源目录(模拟数据)上读取JSON文件的最佳方法是什么?
发布于 2022-04-04 22:47:50
你只需要稍微改变一下你的功能..。
private fun getJSONFromAssets(context: Context): String? {
...
val myUsersJsonFile = context.assets.open("users.json")
...
}假设您的json文件位于src/main/assets。
如果您需要从src/main/res/raw文件夹读取JSON文件。您可以使用:
private fun getJSONFromAssets(context: Context): String? {
...
val myUsersJsonFile = context.resources.openRawResource(R.raw.users)
...
}如您所见,您需要一个Context,因此您可以从您的活动中调用。
getJSONFromAssets(this) // "this" is your activity (or another Context)https://stackoverflow.com/questions/71742665
复制相似问题