kotlin - 无法为 retrofit2.Call 调用无参数构造函数
问题描述
我有以下改造单例:
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 )
}
}
}
我的响应.kt
data class MyResponse(
val listOfData: List<DataEntity>
)
数据实体.kt
data class DataEntity(
@SerializedName("name")
val fullName: String
}
我通过以下方式从 ModelView 调用代码:
viewModelScope.launch {
try {
val webResponse = MyAPI.create().fetchData().await()
Log.d( tag, webResponse.toString() )
}
catch ( e : Exception )
{
Log.d( tag, "Exception: " + e.message )
}
}
但我不断得到:
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.
我似乎无法找到解决这个问题的方法。请给点提示?
编辑:
JSON 响应:
[
{
"name": "A"
},
{
"name": "B"
},
{
"name": "C"
}
]
解决方案
问题是您尝试suspend
与Call<T>
返回类型结合使用。使用suspend
时,应该让 Retrofit 函数直接返回数据,如下所示:
suspend fun fetchData() : List<DataEntity> // Note: Not MyResponse, see below
然后,您所要做的就是.await()
在拨打电话时删除,如下所示:
// Will throw exception unless HTTP 2xx is returned
val webResponse = MyAPI.create().fetchData()
请注意,您根本不应该使用MyResponse
该类,因为 JSON 直接返回一个数组。
推荐阅读
- mysql - 从表中选择具有最大列值的单个条目,其中多个条目具有该值
- excel - VBA Excel根据创建的上一个工作表添加带有编号的新工作表
- python - 如何在 Python 中触发 onClick 事件
- c - 在c中使用高斯模糊模糊图像
- azure-synapse - Azure SQL 数据仓库 (Synapse Analytics) 可以安装在本地吗?
- kubernetes - 使用 Minikube 和 AWS ECS 构建本地测试环境
- apache-spark - Apache Airflow 在* Spark 作业中编排 DAG?
- c - fpclassify(x) == FP_NAN 在功能上是否等同于 isnan(x)?
- javascript - SVG 图表使用 Canvg 转换错误
- openshift - Openshift 集群 - Github webhook 不工作