来自JSON的GSON需要开始_OBJECT,但在路径$的第1行第2列却是BEGIN_ARRAY

wnavrhmk  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(214)

我正在尝试将字符串转换为JSONArray,但遇到了问题。
这是我的考验:

class MainActivityTest {

    @Test
    fun checkParse(){
        val loader = ClassLoader.getSystemClassLoader()
        val json: String = Files.lines(
            get(
                loader.getResource("data.json").toURI()
            )
        )
            .parallel()
            .collect(Collectors.joining())
        val main = MainActivity()
        val dataParse2 = Gson().fromJson(json, JSONArray::class.java)
        val gson = GsonBuilder().create()
        val parse2 = gson.fromJson(json, Array<QuoteModel>::class.java).toList()
        val parse1 = main.parseResponse(dataParse2)

        assertEquals(parse1,parse2)
    }

}

这是我在MainActivity中测试的函数:

fun parseResponse(response: JSONArray): List<QuoteModel> {
    val fileData = response.toString()
    val gson = GsonBuilder().create()
    return gson.fromJson(fileData, Array<QuoteModel>::class.java).toList()
}

这是我的data.json文件:

[
  {
    "text": "Genius is one percent inspiration and ninety-nine percent perspiration.",
    "author": "Thomas Edison"
  },
  {
    "text": "You can observe a lot just by watching.",
    "author": "Yogi Berra"
  },
  {
    "text": "A house divided against itself cannot stand.",
    "author": "Abraham Lincoln"
  }
]

这个问题来自我的测试:
如果class.java。
有什么想法吗?

首次更新

这是我在MainActivity中调用parseFunction的函数:

private fun jsonArrayRequest(url: String): JsonArrayRequest {
    return JsonArrayRequest(Request.Method.GET, url, null,
        { response ->

            val quotesArray = parseResponse(response)
            displayQuote(chooseQuote(quotesArray))
        },
        { error ->
            TODO("Handle error missing")
        }
    )
}
kxkpmulp

kxkpmulp1#

private fun jsonArrayRequest(url: String): JsonArrayRequest {
return JsonArrayRequest(Request.Method.GET, url, null,
        { response ->

            val responseArray = JSONArray(response)
            val quotesArray = parseResponse(responseArray)
            displayQuote(chooseQuote(quotesArray))
        },
        { error ->
            TODO("Handle error missing")
        }
)

fun parseResponse(response: JSONArray): List<QuoteModel> {
return Gson().fromJson(response.toString(), Array<QuoteModel>::class.java).toList()

相关问题