【问题标题】:How to read json file from assests in android using Kotlin?如何使用 Kotlin 从 android 中的资产中读取 json 文件?
【发布时间】:2019-11-19 14:28:29
【问题描述】:

我已经使用过 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 中的这段代码。

【问题讨论】:

    标签: android json kotlin


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      Java 代码也可以从 Android Studio 转换为 Kotlin。 这是Context扩展功能的转换解决方案。

      @Throws(IOException::class)
      fun Context.readJsonAsset(fileName: String): String {
          val inputStream = assets.open(fileName)
          val size = inputStream.available()
          val buffer = ByteArray(size)
          inputStream.read(buffer)
          inputStream.close()
          return String(buffer, Charsets.UTF_8)
      }
      

      【讨论】:

        【解决方案3】:

        你可以使用下面的

        class LocalJSONParser {
        
        companion object {
            fun inputStreamToString(inputStream: InputStream): String {
                try {
                    val bytes = ByteArray(inputStream.available())
                    inputStream.read(bytes, 0, bytes.size)
                    return String(bytes)
                } catch (e: IOException) {
                    return ""
                }
              }
            }
        }
        
        // jsonFileName = "data.json"
        inline fun <reified T> Context.getObjectFromJson(jsonFileName: String): T {
        val myJson =LocalJSONParser.inputStreamToString(this.assets.open(jsonFileName))
        return Gson().fromJson(myJson, T::class.java
        }
        

        【讨论】:

          猜你喜欢
          • 2015-05-04
          • 2018-11-14
          • 2019-05-26
          • 2013-10-06
          • 1970-01-01
          • 1970-01-01
          • 2021-12-11
          • 1970-01-01
          • 2020-11-27
          相关资源
          最近更新 更多