【问题标题】:How to create an arraylist from JSON in Kotlin?如何在 Kotlin 中从 JSON 创建一个数组列表?
【发布时间】:2020-10-28 17:01:06
【问题描述】:

我是 Kotlin 的新手,我正在尝试从 Json 文件创建一个数组列表,但我不明白为什么它不起作用。 这是我的 Json:

{
  "bottomApp": "com.android.contacts",
  "topApp": "com.android.chrome"
}{
  "bottomApp": "com.android.camera2",
  "topApp": "com.google.android.apps.docs"
}

还有代码。评论中有我的尝试。

data class ApplicationInfo(
        var topApp: String? = null,
        var bottomApp: String? = null,
        var tIcon: Drawable? = null,
        var bIcon: Drawable? = null) {

companion object {

        internal inline fun <reified T> Gson.fromJson(json: String) = fromJson<T>(json, object : TypeToken<T>() {}.type)

        fun getShortcuts(context: Context, filename: String): ArrayList<ApplicationInfo> {
            var shortcutList = ArrayList<ApplicationInfo>()

            try {
                // Load data
                val jsonString = loadJson("dataj.json", context)
                val gson = Gson()
                // 1
                // val scType = object : TypeToken<ArrayList<ApplicationInfo>>() {}.type
                // shortcutList = gson.fromJson<ArrayList<ApplicationInfo>>(jsonString, scType)

                //2
                // shortcutList = gson.fromJson(jsonString, Array<ApplicationInfo>::class.java).toList() as ArrayList<ApplicationInfo>

                //3
                shortcutList = gson.fromJson(jsonString.toString())


                Log.i("RESULT", shortcutList.toString())

                //Log.i("APPLIST", appList.toString())
            } catch (e: JSONException) {
                e.printStackTrace()
            }
            return shortcutList
        }

...

还有错误:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT

【问题讨论】:

  • 你的 json 文件好像不是数组
  • 可以分享完整的json文件,否则就是完整的文件?
  • 这是无效的 Json 表示,没有数组字面量 ([...]),两个 json 对象之间也没有逗号。
  • 是的,这是我用 gson 创建的完整文件:
  • 也许你和here有同样的问题,我不明白为什么人们使用PHP一次回显一半的json...

标签: android json kotlin gson


【解决方案1】:

您好,您的 json 文件内容必须是

[
   {
      "bottomApp":"com.android.contacts",
      "topApp":"com.android.chrome"
   },
   {
      "bottomApp":"com.android.camera2",
      "topApp":"com.google.android.apps.docs"
   }
]

【讨论】:

    猜你喜欢
    • 2018-01-31
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    • 2022-07-29
    • 2019-09-26
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    相关资源
    最近更新 更多