【发布时间】:2018-03-28 16:26:00
【问题描述】:
我正在使用 Google HTTP 客户端发出 API 请求,我希望使用 parseAs() 方法为我反序列化 JSON 响应。我的模型是 Kotlin 数据类,但反序列化器无法实例化我的类:
Caused by: java.lang.IllegalArgumentException: unable to create new instance of class com.ippontech.blog.stats.model.GitFile because it has no accessible default constructor
这是我的 Kotlin 数据类:
data class GitFile(
val name: String,
@SerializedName("download_url") val downloadUrl: String)
以及我使用的代码:
val requestFactory = NetHttpTransport().createRequestFactory{
it.setParser(JsonObjectParser(GsonFactory()))
}
val request = requestFactory.buildGetRequest(
GenericUrl("https://api.github.com/repos/ippontech/blog-usa/contents/posts"))
val type = object : TypeToken<List<GitFile>>() {}.type
val rawResponse = request.execute().parseAs(type)
另一方面,如果我将响应作为字符串检索,然后使用 Gson 解析器,它可以正常工作:
val requestFactory = NetHttpTransport().createRequestFactory()
val request = requestFactory.buildGetRequest(
GenericUrl("https://api.github.com/repos/ippontech/blog-usa/contents/posts"))
val rawResponse = request.execute().parseAsString()
val type = object : TypeToken<List<GitFile>>() {}.type
val gitFiles: List<GitFile> = Gson().fromJson(rawResponse, type)
这似乎表明JsonObjectParser 在这里没有完成它的工作。
我正在使用的版本:
compile 'org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.2.30'
compile 'com.google.code.gson:gson:2.8.0'
compile 'com.google.apis:google-api-services-sheets:v4-rev512-1.23.0'
compile 'com.google.api-client:google-api-client-gson:1.23.0'
知道如何解决这个问题吗?
【问题讨论】: