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());
}
}
1条答案
按热度按时间amrnrhlw1#
以下是使用gson时应该执行的步骤
1.获取单独在“results”中的json对象的键
1.将其作为具有键和值的json对象获取
1.收集JSON的条目集
1.创建一个迭代器,以便以后可以提取密钥
下面是执行相同工作的代码:
**代码编辑:**What @fluffy pointed完全有意义。进行了更改