Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
914 views
in Technique[技术] by (71.8m points)

json - Java GSON: Getting the list of all keys under a JSONObject

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:

{ "The Object I already know": {
"key1":"value1",
"key2":"value2",
"AnotherObject": { "anotherKey1":"anotherValue1", "anotherKey2":"anotherValue2" }
}

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.
EDIT: The Output should be a String Array with all the keys for the JSONObject

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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}";
JsonElement element = JsonParser.parseString(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());
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...