java - 将 Json 字符串转换为 JsonObject 对象
问题描述
我有以下 JSON:
{
"insertId":"qxdo1se4pjcw",
"logName":"projects,
"protoPayload":{
"type":"type.googleapis.com/google.cloud.audit.AuditLog",
"authenticationInfo":{
"principalEmail":"gserviceaccount.com"
},
"authorizationInfo":[
{
"granted":true,
"permission":"bigquery.tables.updateData",
"resource":"metrics_event",
"resourceAttributes":{
}
}
]
}
我想将其转换为 JSON 对象,以便稍后我们可以轻松引用每个对象我的代码:
String msg = message.getData().toStringUtf8();
JsonParser pa = new JsonParser();
JsonObject obj = (JsonObject) pa.parse(msg);
我可以使用 get 方法访问元素,但是如何访问嵌套的元素,例如
obj.get("protoPayload"
) 工作正常,但如何访问type
如同obj.get("protoPayload").get("type")
解决方案
使用来自 org.json 的纯 JSON
JSONObject json=new JSONObject(String source);
这会将有效的 JSON 字符串转换为 JSON 对象。
如果您想访问 JSON 中的嵌套对象并且您已经知道“密钥”,那么您可以使用以下内容。
JSONObject 扩展了 HashMap,因此您可以简单地将其用作 HashMap:
JSONObject jsonChildObject = (JSONObject)jsonObject.get("protoPayload");
for (Map.Entry in jsonChildOBject.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
推荐阅读
- python - 如何在嵌入 3D 的表面上绘制测地线曲线?
- configuration - 如何在 kubeflow 中为 jupyter notebook 服务器添加配置(例如环境变量)
- c++ - 如何删除 LLVM 中的非条件分支?
- python - 使用 kubernetes 并行化一个简单的 python 脚本
- sql - HIVE - 导出到 Excel 时从标题中删除数据库名称
- arguments - 如何编写一个函数来在 RStudio 中查找某个范围内的素数
- firebase - 领域崩溃:com.apple.main-thread EXC_BAD_ACCESS KERN_INVALID_ADDRESS RLMUtil.hpp RLMIsObjectSubclass
- powershell - Azure 创建拉取请求 API 引发错误:“参数值无效。需要源引用和目标引用。”
- c# - 检测到布局周期。布局无法完成,对于 UWP 中的 Flyout
- d3.js - D3 树形图:版本 4 中链接(路径)上的文本