gpt4 book ai didi

java - Android:从 sampledata 文件夹中读取 json

转载 作者:行者123 更新时间:2023-12-02 00:12:17 25 4
gpt4 key购买 nike

我想用我的自定义 operations.json 文件填充 RecyclerView,该文件保留在 sampledata 文件夹中。我如何读取该示例 json 文件?我的 operations.json 文件如下所示:

{
"data" :[
{ "name": "123", "image": "@drawable/ic_cloud_download_black_24dp" },
{ "name": "456", "image": "@drawable/ic_arrow_forward_black_24dp" },
{ "name": "789", "image": "@drawable/ic_photo_camera_black_24dp" },
{ "name": "asd", "image": "@drawable/ic_alarm_off_black_24dp" },
{ "name": "qwe", "image": "@drawable/ic_assignment_black_24dp" },
{ "name": "rty", "image": "@drawable/ic_map_black_24dp" },
{ "name": "asd", "image": "@drawable/ic_sms_black_24dp" },
{ "name": "fgh", "image": "@drawable/ic_print_black_24dp" },
{ "name": "zxc", "image": "@drawable/ic_library_books_black_24dp" },
{ "name": "vbn", "image": "@drawable/ic_settings_black_24dp" },
{ "name": "jkl", "image": "@drawable/ic_android_black_24dp" },
{ "name": "yui", "image": "@drawable/ic_tv_black_24dp" },
{ "name": "ert", "image": "@drawable/ic_exit_to_app_black_24dp" }
]
}

最佳答案

  • 首先创建 Assets 文件夹
  • 将您的 json 文件放在 Assets 文件夹中

    Asset folder

  • 按照代码读取json文件

    私有(private)乐趣 loadJSONFromAsset():字符串? {
    val json:字符串?
    尝试 {
    val inputStream = activity!!.assets.open("search_key.json")
    val size = inputStream.available()
    val buffer = ByteArray(大小)
    inputStream.read(缓冲区)
    inputStream.close()
    json = 字符串(缓冲区,字符集.UTF_8)
    } catch (例如:IOException){
    前.printStackTrace()
    返回空
    }
    返回json
    }

  • 使用 GSON 库解析你的 json

    val data = Gson().fromJson(loadJSONFromAsset(), Data::class.java)

关于java - Android:从 sampledata 文件夹中读取 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58585330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com