我有以下改造单身人士:
interface MyAPI
{
@GET("/data.json")
suspend fun fetchData() : Call<MyResponse>
companion object
{
private val BASE_URL = "http://10.0.2.2:8080/"
fun create(): MyAPI
{
val gson = GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create()
val retrofit = Retrofit.Builder()
.addConverterFactory( GsonConverterFactory.create( gson ) )
.baseUrl( BASE_URL )
.build()
return retrofit.create( MyAPI::class.java )
}
}
}
Run Code Online (Sandbox Code Playgroud)
MyResponse.kt
data class MyResponse(
val listOfData: List<DataEntity>
)
Run Code Online (Sandbox Code Playgroud)
数据实体.kt
data class DataEntity(
@SerializedName("name")
val fullName: String
}
Run Code Online (Sandbox Code Playgroud)
我通过以下方式从 ModelView 调用代码:
viewModelScope.launch {
try {
val webResponse = MyAPI.create().fetchData().await()
Log.d( tag, webResponse.toString() )
}
catch ( e : Exception )
{
Log.d( tag, "Exception: " + e.message )
}
}
Run Code Online (Sandbox Code Playgroud)
但我不断得到:
Unable to invoke no-args constructor for retrofit2.Call<com.host.myproject.net.response.MyResponse>. Registering an InstanceCreator with Gson for this type may fix this problem.
Run Code Online (Sandbox Code Playgroud)
我似乎无法找到解决此问题的方法.. 有什么提示吗?
编辑:
JSON 响应:
[
{
"name": "A"
},
{
"name": "B"
},
{
"name": "C"
}
]
Run Code Online (Sandbox Code Playgroud)
Ens*_*lic 28
问题是您尝试suspend与Call<T>返回类型结合使用。使用的时候suspend应该让 Retrofit 函数直接返回数据,像这样:
suspend fun fetchData() : List<DataEntity> // Note: Not MyResponse, see below
Run Code Online (Sandbox Code Playgroud)
然后你要做的就是.await()在你打电话的时候删除,就像这样:
// Will throw exception unless HTTP 2xx is returned
val webResponse = MyAPI.create().fetchData()
Run Code Online (Sandbox Code Playgroud)
请注意,您根本不应使用MyResponse该类,因为 JSON 直接返回一个数组。
第 1 步:删除呼叫并处理响应
前:
@POST("list")
suspend fun requestList(@Body body: JsonObject): call<Profile>
Run Code Online (Sandbox Code Playgroud)
后
@POST("list")
suspend fun requestList(@Body body: JsonObject): Profile
Run Code Online (Sandbox Code Playgroud)
步骤2:删除挂起并处理响应
@POST("list")
fun requestList(@Body body: JsonObject): call<Profile>
Run Code Online (Sandbox Code Playgroud)
小智 7
我有同样的问题,检查我的模型没问题后。然后我尝试删除接口 API 上的挂起。
@GET("/data.json")
suspend fun fetchData() : Call<MyResponse>
Run Code Online (Sandbox Code Playgroud)
成为
@GET("/data.json")
fun fetchData() : Call<MyResponse>
Run Code Online (Sandbox Code Playgroud)
它解决了(错误 Unable to invoke no-args constructor for Retrofit2.Call 已经消失)。
| 归档时间: |
|
| 查看次数: |
3854 次 |
| 最近记录: |