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

Sau*_*Rai 5 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;
}
Run Code Online (Sandbox Code Playgroud)

我想要 Kotlin 中的这段代码。

m.k*_*.ka 18

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

val fileInString: String =
  applicationContext.assets.open(fileName).bufferedReader().use { it.readText() }
Run Code Online (Sandbox Code Playgroud)