如何在 android studio 中通过 Retrofit、Coroutine with Kotlin 解析 JSON 数据

How to parse JSON data through Retrofit, Coroutine with Kotlin in android studio

我正在为 JSON 解析编写代码,但未检索到 JSON 数据。会是什么问题?

下面是数据对象class

data class UsersItem(
    val avatar_url: String,
    val events_url: String,
    val followers_url: String,
    val following_url: String,
    val gists_url: String,
    val gravatar_id: String,
    val html_url: String,
    val id: Int,
    val login: String,
    val node_id: String,
    val organizations_url: String,
    val received_events_url: String,
    val repos_url: String,
    val site_admin: Boolean,
    val starred_url: String,
    val subscriptions_url: String,
    val type: String,
    val url: String
)

下面是定义的List

class Users : ArrayList<UsersItem>()

下面是 ApiUtilities

object ApiUtilities {
    private val BaseURl = "https://api.github.com/"

    fun getInstance(): Retrofit {
        return Retrofit.Builder().baseUrl(BaseURl)
            .addConverterFactory(GsonConverterFactory.create()).build()
    }
}

下面是ApiInterface

interface ApiInterface {
@GET("/Users")
suspend fun getUsers(): Response<Users>
}

下面是MainActivity, 我刚刚测试了获取带有登录 ID 的 JSON 响应,但我没有得到结果。 请更正代码或提出任何建议

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val helloTxt = findViewById<TextView>(R.id.txt) as TextView
        val userApi = ApiUtilities.getInstance().create(ApiInterface::class.java)

        GlobalScope.launch {
            val result = userApi.getUsers()
            if (result.isSuccessful && result.body() != null) {
                result.body()?.forEach {
                    Toast.makeText(this@MainActivity, "${it.id}", Toast.LENGTH_LONG).show()
                    Log.d("Manju", "${it.login}")
                    helloTxt.setText("${it.login}")
                }

            }
        }

    }
}

我认为你应该使用带有小写“u”的“/users”:

interface ApiInterface {
@GET("/users")
suspend fun getUsers(): Response<Users>
}

而不是:

interface ApiInterface {
@GET("/Users")
suspend fun getUsers(): Response<Users>
}