Java GSON:获取JSONObject下所有键的列表 [英] Java GSON: Getting the list of all keys under a JSONObject
问题描述
我已经在Java中使用GSON作为JSON解析器,但密钥并不总是相同的。
例如。我有以下JSON:
I have got GSON as a JSON parser in Java, but the keys aren't always the same.
For example. I have the following JSON:
{我已经知道的对象:{/ /
key1: value1,
key2:value2,
AnotherObject:{anotherKey1:anotherValue1,anotherKey2:anotherValue2}
}
{ "The Object I already know": {
"key1":"value1",
"key2":"value2",
"AnotherObject": { "anotherKey1":"anotherValue1", "anotherKey2":"anotherValue2" }
}
我已经有了JSONObjectThe Object I already know。现在我需要获取这个对象的所有JSONElements,这将是Key1,Key2和AnotherObject。
在此先感谢。
编辑:输出应该是一个包含JSONObject所有键的字符串数组
I have already got the JSONObject "The Object I already know". Now I need to get all of the JSONElements for this Object, this would be "Key1", "Key2" and "AnotherObject".
Thanks in advance.
The Output should be a String Array with all the keys for the JSONObject
推荐答案
您可以使用JsonParser将Json转换为中间结构允许您检查json内容。
You can use JsonParser to convert your Json into an intermediate structure which allow you to examine the json content.
String yourJson = "{your json here}";
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(yourJson);
JsonObject obj = element.getAsJsonObject(); //since you know it's a JsonObject
Set<Map.Entry<String, JsonElement>> entries = obj.entrySet();//will return members of your object
for (Map.Entry<String, JsonElement> entry: entries) {
System.out.println(entry.getKey());
}
这篇关于Java GSON:获取JSONObject下所有键的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!