我试图从https://github.com/users获取json。 我想显示用户名:yehezkiell,例如https://github.com/yehezkiell。 改进显示成功结果,但始终返回null。我是这次改造的新手,请帮忙
这是我的代码
val postService = DataRepository.create()
postService.getUser("yehezkiell").enqueue(object : Callback<Users>{
override fun onFailure(call: Call<Users>?, t: Throwable?) {
Log.e("retrofitnya","gagal ${t}")
}
override fun onResponse(call: Call<Users>?, response: Response<Users>?) {
Log.e("retrofitnya","berhasil")
val data = response?.body()
Log.e("retrofitnya","berhasil ${data?.name}")
}
})
改造实例
interface RetrofitInstance {
@GET("users/{username}")
fun getUser(@Path("username") username:String ): Call<Users>
}
数据仓库
object DataRepository {
fun create(): RetrofitInstance {
val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://github.com")
.build()
return retrofit.create(RetrofitInstance::class.java)
}
}
Users.kt
open class Users {
@SerializedName("name")
@Expose
open var name: String? = null
@SerializedName("username")
@Expose
open var username: String? = null
@SerializedName("email")
@Expose
open var email: String? = null
}
答案 0 :(得分:0)
对于调试过程,我们应该执行以下操作,而不是在响应后立即对Users
对象进行反序列化? :
interface RetrofitInstance {
@GET("users/{username}")
fun getUser(@Path("username") username: String): Call<String>
}
override fun onResponse(call: Call<String>?, response: Response<String>?) {
val responseBody = response?.body() ?: ""
Log.e("retrofitnya","response body as string = ${responseBody}")
}
Users
),请手动对其进行反序列化。val user: Users = Gson().fromJson(responseBody, Users::class.java)
如果不太保密,请给我们提供如何声明Users
数据对象的信息,例如Foo和Bar。
data class Foo(
@SerializedName("bar") val bar: Bar?
)
data class Bar(
@SerializedName("name") val name: String?
)
答案 1 :(得分:0)
我自己解决了这个问题,实际上这是我愚蠢的错过理解,这是终点是错误的。
In my wrong code
object DataRepository {
fun create(): RetrofitInstance {
val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://github.com")
.build()
return retrofit.create(RetrofitInstance::class.java)
}
}
那个错误的终点是
https://github.com
真正的是
https://api.github.com/