java - Java从嵌套的json中提取键值
问题描述
我确实有以下 JSON,我正在尝试在结果中提取对象
{
"status":true,
"results":{
"type1":{
"id":"type1"
},
"type2":{
"id":"type2"
}
}
}
所需的输出是
type1,type2
我正在使用 Gson 进行序列化和反序列化。
解决方案
这些是您在使用 gson 时应该执行的步骤
- 获取单独在“结果”中的 json 对象的键
- 将其作为具有键和值的 json 对象获取
- 收集我们的 JSON 的条目集
- 创建一个迭代器,以便稍后您可以提取键
这是执行相同工作的代码:
public static void main(String[] args) throws Exception {
String json = "{\r\n" +
" \"status\":true,\r\n" +
" \"results\":{\r\n" +
" \"type1\":{\r\n" +
" \"id\":\"type1\"\r\n" +
" },\r\n" +
" \"type2\":{\r\n" +
" \"id\":\"type2\"\r\n" +
" }\r\n" +
" }\r\n" +
"}";
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(json).getAsJsonObject();
//get keys of the json objects which are inside "results" alone
//get it as json object which has keys and values
//collect the entry set our of the JSON
//create an iterator so that later you can extract the keys
Iterator<Entry<String, JsonElement>> iterator = obj.get("results")
.getAsJsonObject()
.entrySet()
.iterator();
while(iterator.hasNext()) {
//here you will get the keys like - type1 and type2
System.out.println(iterator.next().getKey());
}
}
代码编辑: @fluffy 指出的内容完全有意义。做出改变
推荐阅读
- ios - 在轴图 ios 上同时使用字符串和日期
- excel - VBA 使用 COUNTIFS 作为公式
- python - 退出代码 -1 的含义
- python - 如何使用 pathlib.Path().glob() 读取文件并将具有相同文件名的文件输出到另一个子文件夹
- .net-core - 如何从现有数据库创建迁移
- python - 无法在 python 中加载 csv 文件
- php - 通过 get_post_meta() 获取产品插件信息
- javascript - 合并包含数组的对象数组
- json - 将 Json 转换为 Avro 架构
- sql - 如果我从一个完全不相关的表中更新一个表,MS SQL Server 会做什么