android - 如何一次从 JSON 对象中检索多个项目
问题描述
我试图在同一次传递中从下面的 JSON 中检索多个项目。我希望将每个“序列”实例的每个 originatorId 和消息检索为有序格式,以便我可以在回收器视图中显示它们,就像消息传递历史一样。
到目前为止,我已经尝试通过 Klaxon 使用模式匹配,但无法让它挑选出多个“消息”实例。我认为我的问题是找到一种方法来获取“更改”对象的每个实例,而不仅仅是第一个例如=
"$.body.changes.event.message" -> does not work
"$.body.changes[0].event.message" -> returns only first message
{
"kind": "notification",
"body":
{
"changes": [
{
"sequence": 0,
"originatorId": "d5305f84f7812530e746a713ebeabb457e59b380b779387de90ff0f7ff593e2a",
"originatorMetadata":
{
"id": "d5305f84f7812530e746a713ebeabb457e59b380b779387de90ff0f7ff593e2a",
"role": "CONSUMER"
},
"serverTimestamp": 1555330963355,
"event":
{
"type": "ContentEvent",
"message": "hello ",
"contentType": "text/plain"
},
"dialogId": "8e35bc87-c42f-4a28-837d-ac6d93cb119a"
},
{
"sequence": 2,
"originatorId": "73c29cd1-b3e3-56fc-a483-ba3409831d21",
"originatorMetadata":
{
"id": "73c29cd1-b3e3-56fc-a483-ba3409831d21",
"role": "ASSIGNED_AGENT"
},
"serverTimestamp": 1555330964870,
"event":
{
"type": "ContentEvent",
"message": "Hi Bob, how can I help you today? ",
"contentType": "text/plain"
},
"dialogId": "8e35bc87-c42f-4a28-837d-ac6d93cb119a"
},
{
"sequence": 3,
"originatorId": "d5305f84f7812530e746a713ebeabb457e59b380b779387de90ff0f7ff593e2a",
"originatorMetadata":
{
"id": "d5305f84f7812530e746a713ebeabb457e59b380b779387de90ff0f7ff593e2a",
"role": "CONSUMER"
},
"serverTimestamp": 1555330975711,
"event":
{
"type": "ContentEvent",
"message": "hi",
"contentType": "text/plain"
},
"dialogId": "8e35bc87-c42f-4a28-837d-ac6d93cb119a"
}
我的预期结果将是某种形式的地图,其中 originatorId 与映射位置链接到序列的消息。目前,我只能将第一条消息“hello”和最后一个 originatorId 链接在一起。进一步的工作将包括将 serverTimestamp 导出到相同的映射中。我愿意对 Klaxon 使用不同的库。
这是我已经尝试使用的代码=
val pathMatcher = object : PathMatcher {
override fun pathMatches(path: String) = Pattern.matches(".*.message", path)
override fun onMatch(path: String, value: Any) {
val origin = parseForOriginatorId(text)
val messageNew = Message(origin, timeReadNew, value.toString())
ChatActivity.adapter.addMessage(Message(origin, timeReadNew, value.toString()))
//messages[origin] = messageNew
Log.d("D", "Message: ${messageNew.originator}: ${messageNew.content}")
when (path) {
"$.body.changes.originatorId" -> Log.d("D", "======originator ID $value" )
"$.body.changes.event.message" -> Log.d("D", "=====Message $value")
}
}
}
Klaxon().pathMatcher(pathMatcher)
.parseJsonObject(StringReader(text))
}
解决方案
循环遍历数组(示例)
val myJsonArray = json.get("changes") as JSONArray
for (i in 0..(myJsonArray.length() - 1)) {
val item = myJsonArray[i] as JSONObject
}
推荐阅读
- python - 如何将嵌套循环转换为惯用的 numpy 代码以创建锦标赛结果矩阵?
- amazon-web-services - 如何在 aws_policy.arn 中使用列表 terraform 变量的值
- ssas - SSAS 多维数据集中选定时间属性层次结构的 PY 总计
- video - 是否可以通过 MPD 文件更改 MP4 片段加载(使用 SHAKA 播放器)
- python - 有没有办法找到 min 函数选择的变量的名称?
- spring - 使用带有 HibernateDaoSupport 和 SessionFactory 的 AbstractRoutingDataSource
- c# - EF Core 5检查过滤器中的所有ID是否存在于相关实体中
- reactjs - React 'load' 未定义 no-undef
- python - 无法从数据库 django 中检索值
- arrays - 将 json 从 db 传递到刀片模板