android - 如何使用 Kotlin 从 android 中的 Assets 中读取 json 文件?

标签 android json kotlin

我已经使用过 java,但发现使用 Kotlin 很困难。

我已经用谷歌搜索过,但它们都不适合我。

/**
 * Get the json data from json file.
 *
 * @param context  the context to acces the resources.
 * @param fileName the name of the json file
 * @return json as string
 */
public static String getJsonFromAsset(Context context, String fileName) {
    String json = "";
    try {
        InputStream stream = context.getAssets().open(fileName);
        int size = stream.available();
        byte[] buffer = new byte[size];
        stream.read(buffer);
        stream.close();
        json = new String(buffer, "UTF-8");

    } catch (Exception e) {
        e.printStackTrace();
    }
    return json;
}

我想要 Kotlin 中的这段代码。

最佳答案

从 Kotlin 的 assets 文件夹中读取 json 文件非常简单,只需使用以下代码

val fileInString: String =
  applicationContext.assets.open(fileName).bufferedReader().use { it.readText() }

关于android - 如何使用 Kotlin 从 android 中的 Assets 中读取 json 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56962608/

相关文章:

java - 所有 Activity 中都可用的选项菜单

android - Actionbar setTitle() 在 OnPageChangeListener() 中只工作一次

android - 当我在 Kotlin 中使用 Anko 时,如何为 SQLite 的表定义一个非空字段?

android - 如何在 android 中使用 volley 对自定义对象进行 post 调用

mysql - 在 JSON 字段数组中搜索缺少属性的记录 (MySQL)

php - 如何在 PHP 中正确 json_encode ["number"=> 12, "color"=> "1e3673"]?

java - 将 json 参数发布到 REST 服务时出错

android - 播放所需文件夹中的音频文件

android - 如何将短信内容保存到文本文件

android - adb shell 命令检查 apk 是调试还是发布签名?