android - 我应该如何在数组中解析 Json
问题描述
我试图在数组中解析 Json 但它不起作用。来源是这样的
@POST("/storyGet")
fun getStory() : Call<ArrayList<StoryData>>
这是 API.kt 和
Client.retrofitService.getStory().enqueue(object :
retrofit2.Callback<ArrayList<StoryData>> {
override fun onResponse(call: Call<ArrayList<StoryData>>?, response: Response<ArrayList<StoryData>>?) {
val repo = response!!.body()
when (response.code()) {
200 -> {
repo!!.indices.forEach {
items += StoryDataSubListItem(
repo[it][it][it].alreadyWatch,
repo[it][it][it].createdAt,
repo[it][it][it].imgUrl,
repo[it][it][it].storyUUID,
repo[it][it][it].userName,
repo[it][it][it].userName,
repo[it][it][it].userUUID
)
recyclerView!!.adapter?.notifyDataSetChanged()
}
}
}
}
override fun onFailure(call: Call<ArrayList<StoryData>>?, t: Throwable?) {
}
})
这是我的改造数据和
class StoryData : ArrayList<StoryDataSubList>()
这是第一个数组和
class StoryDataSubList : ArrayList<StoryDataSubListItem>()
这是我的第二个数组
data class StoryDataSubListItem(
val alreadyWatch: List<Any>,
val createdAt: String,
val imgUrl: String,
val storyUUID: String,
val userName: String,
val userProfileImgUrl: String,
val userUUID: String)
这是数组格式的数组中的数据类和json
[
[
{
"alreadyWatch": [],
"createdAt": "test",
"_id": "_id",
"userUUID": "userUUID2",
"userName": "userName2",
"userProfileImgUrl": "false",
"imgUrl": "imageUrl",
"storyUUID": "StoryUUID",
"__v": 0
}
],
[
{
"alreadyWatch": [],
"createdAt": "test",
"_id": "_id",
"userUUID": "userUUID",
"userName": "TEST NAME",
"userProfileImgUrl": "false",
"imgUrl": "imageURL",
"storyUUID": "StoryUUID",
"__v": 0
}
]]
当我看到logcat时,服务器在这样的情况下正常运行我应该如何修复它?请帮助并提前感谢您。
解决方案
您需要如下更改您的代码,因为响应包含另一个给定模型数据列表的列表,
@POST("/storyGet")
fun getStory() : Call<List<List<StoryDataSubList>>>
完整代码如下
@POST("/storyGet")
fun getStory() : Call<List<List<StoryDataSubList>>>
方法调用改造 API 以获取如下响应
private fun loadStoryData() {
val call = netWorkApi.getStory() // replace netWorkApi with your retrofit API sevice
call.enqueue(object : Callback<List<List<StoryDataSubList>>> {
override fun onResponse(
call: Call<List<List<StoryDataSubList>>>,
response: Response<List<List<StoryDataSubList>>>
) {
if (response.isSuccessful) {
for (index in response.body()?.indices!!)
Log.d("TAG", "${response.body()!!.get(index)}")
}
}
override fun onFailure(call: Call<List<List<StoryDataSubList>>>, t: Throwable) {
TODO("Not yet implemented")
}
});
}
推荐阅读
- python - 有没有办法概括 Spacy 的 retokenizer.split 的论点中的正交?
- html - 导航栏打不开
- kubernetes - 从集群内部连接到 Kafka Kubernetes 集群
- go - 带有外键的Gorm简单查找不起作用
- c# - 将数据填入类
- javascript - 如何为 Rust 和 Javascript 定义一次常量?
- python - 无法打开文件'import.py':[Errno 2] 没有这样的文件或目录
- django - OperationalError at ...没有这样的列:funcionarios_funcionario.user_id
- python - 基于python脚本的django自定义命令
- python - 将索引值移动到熊猫数据框中的列名中