我有以下改造单例:
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.
我似乎找不到这个问题的解决方案..有什么提示吗?
EDIT:
JSON 响应:
[
{
"name": "A"
},
{
"name": "B"
},
{
"name": "C"
}
]
问题是你尝试结合suspend
with a 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 直接返回一个数组,所以根本不需要类。
Update:
您还可以使用Response<DataEntity>
如果您需要标题中的信息
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)