问题描述
我目前正在尝试从JSON对象中的特定字段获取数据。该API是Github API,我尝试实现的功能是搜索。 API结果看起来像这样
{
"total_count": 70,"incomplete_results": false,"items": [
{
"login": "wirya","id": 2296318,"node_id": "MDQ6VXNlcjIyOTYzMTg=","avatar_url": "https://avatars2.githubusercontent.com/u/2296318?v=4","gravatar_id": "","url": "https://api.github.com/users/wirya","html_url": "https://github.com/wirya","followers_url": "https://api.github.com/users/wirya/followers","following_url": "https://api.github.com/users/wirya/following{/other_user}","gists_url": "https://api.github.com/users/wirya/gists{/gist_id}","starred_url": "https://api.github.com/users/wirya/starred{/owner}{/repo}","subscriptions_url": "https://api.github.com/users/wirya/subscriptions","organizations_url": "https://api.github.com/users/wirya/orgs","repos_url": "https://api.github.com/users/wirya/repos","events_url": "https://api.github.com/users/wirya/events{/privacy}","received_events_url": "https://api.github.com/users/wirya/received_events","type": "User","site_admin": false,"score": 1.0
},{
"login": "wiryawan46","id": 16128117,"node_id": "MDQ6VXNlcjE2MTI4MTE3","avatar_url": "https://avatars0.githubusercontent.com/u/16128117?v=4","url": "https://api.github.com/users/wiryawan46","html_url": "https://github.com/wiryawan46","followers_url": "https://api.github.com/users/wiryawan46/followers","following_url": "https://api.github.com/users/wiryawan46/following{/other_user}","gists_url": "https://api.github.com/users/wiryawan46/gists{/gist_id}","starred_url": "https://api.github.com/users/wiryawan46/starred{/owner}{/repo}","subscriptions_url": "https://api.github.com/users/wiryawan46/subscriptions","organizations_url": "https://api.github.com/users/wiryawan46/orgs","repos_url": "https://api.github.com/users/wiryawan46/repos","events_url": "https://api.github.com/users/wiryawan46/events{/privacy}","received_events_url": "https://api.github.com/users/wiryawan46/received_events","score": 1.0
}
]
}
我只想从"items"
字段中获取数据。如何使用Kotlin语言进行翻新?
我尝试使用的代码如下:
@GET("search/users")
suspend fun searchUsers(@Query("q") q: String): Response<List<User>>
它给我错误预期BEGIN_ARRAY,但在第1行第2列路径$ BEGIN_OBJECT中
更新:这是我的数据类
data class User(
var login: String,var type: String,var avatar_url: String,var public_repos: Int = 0,var followers: Int = 0,var following: Int = 0
)
感谢您的帮助
解决方法
您还需要将“ items”匹配为数据类:
data class Items (
val items: List<User>
)
data class User(
var login: String,var type: String,var avatar_url: String,var public_repos: Int = 0,var followers: Int = 0,var following: Int = 0
)
@GET("search/users")
suspend fun searchUsers(@Query("q") q: String): Response<Items>