【问题标题】:Expected BEGIN_ARRAY but was STRING but JSON is correct预期 BEGIN_ARRAY 但为 STRING 但 JSON 正确
【发布时间】:2019-10-31 07:48:04
【问题描述】:

我已经搜索了其他相关问题,但找不到我的答案。

这是我的 JSON:命名为 appointments.json

   [
  {
    "title": "Primary Care",
    "text": "Schedule a Primary Care appointment online.",
    "image": "http://i.imgur.com/DvpvklR.png"
  },
  {
    "title": "Primary Care",
    "text": "Schedule a Primary Care appointment online.",
    "image": "http://i.imgur.com/DvpvklR.png"
  },
  {
    "title": "Primary Care",
    "text": "Schedule a Primary Care appointment online.",
    "image": "http://i.imgur.com/DvpvklR.png"
  },
  {
    "title": "Primary Care",
    "text": "Schedule a Primary Care appointment online.",
    "image": "http://i.imgur.com/DvpvklR.png"
  }
]

这里是列表对象类:

    @Parcelize
data class AppointmentsListItem(
        @Expose
        @SerializedName("title")
        val title: String = "",
        @Expose
        @SerializedName("text")
        val text: String = "",
        @Expose
        @SerializedName("image")
        val image: String = "") : IAppointmentsListItem

这是我的错误发生的地方:

val gson = GsonBuilder().excludeFieldsWithoutExposeAnnotation()
        .create()

private val listType = object : TypeToken<List<AppointmentsListItem>>() {}.type

    val apiList: List<AppointmentsListItem> = gson.fromJson("appointments.json", listType)

STRING 到底是从哪里来的??我的 Json 响应是这些 ListItems 的数组,我以 [] 开始响应,为什么它读取字符串?

【问题讨论】:

    标签: android arrays json kotlin gson


    【解决方案1】:

    STRING 到底是从哪里来的?

    "appointments.json" 是一个字符串。此外,"appointments.json" 不是有效的 JSON 字符串,因为它以 a 开头,而不是 [{

    我的猜测是 appointments.json 应该是一个文件名。但是,Gson 不知道这一点,而且无论如何,一个裸露的文件名是没有用的。您需要在 JSON 本身上为 Gson 提供 InputStreamReader,无论它来自何处,例如:

    • FileReader(您提供的 File 指向 appointments.json 所在的位置)
    • InputStream 来自 ContentResolveropenInputStream()
    • InputStream 来自 AssetManageropen()

    【讨论】:

    • 哈哈!男人好简单!我确定这是问题所在,一旦我添加 FileReader 并让它工作,我会接受这个答案
    • @Kyle:确保您使用正确的方法来获取您的File 的根目录(例如,getFilesDir())。像appointments.json 这样的裸文件名在Android 中没有任何意义。这个文件在哪里?
    • 是的,我很难找到它位于AppName/ModuleName/src/test/resources/appointments.json,但是执行 FileReader(上面的路径)会返回一个文件未找到异常
    • @Kyle:我没有写过使用Java资源的单元测试,所以我不确定获取InputStream的过程是什么。
    • InputStream = context.getAssets().open(assetName),设置缓冲区,然后读入……知道了……谢谢!
    猜你喜欢
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    • 2016-01-27
    • 2018-11-11
    • 2016-02-18
    • 2019-06-16
    • 2015-11-10
    相关资源
    最近更新 更多