首页 > 解决方案 > 使用 kotlin 在 android studio 中进行 api 调用时遇到问题

问题描述

我想在使用 kotlin 的 android studio 中使用 json 对象请求进行 api 调用。这是api。API 图像

如何访问数组文章中的“名称”?我可以访问除“id”和“name”之外的所有其他内容。这是我的代码

val url = "https://news-api-don.herokuapp.com/api/v1?apiKey=20d14506791144cc8b424549c42068c0"

    val jsonObjectRequest = JsonObjectRequest(
        Request.Method.GET, url, null,
        {
            val newsJsonArray = it.getJSONArray("articles")
            val newsArray = ArrayList<News>()
            for(i in 0 until newsJsonArray.length()) {
                val newsJsonObject = newsJsonArray.getJSONObject(i)
                val news = News(
                    newsJsonObject.getString("title"),
                    newsJsonObject.getString("author"),
                    newsJsonObject.getString("url"),
                    newsJsonObject.getString("urlToImage")
                )
                newsArray.add(news)

            }
            mAdapter.updateNews(newsArray)
            swipeRefreshLayout.isRefreshing = false
            progressBar.visibility = View.GONE

        },
        {
            Toast.makeText(this,"Something went wrong", Toast.LENGTH_LONG).show()
            swipeRefreshLayout.isRefreshing = false
            progressBar.visibility = View.GONE
        }
    )


    MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest)

}

标签: jsonapiandroid-studiokotlin

解决方案


推荐阅读