I have to retrieve all name of fields of JSONObject
in Java. For example, this is a JSON:
{
"name" : {
"first" : "John",
"last" : "McCarthy"
},
"birth" : ISODate("1927-09-04T04:00:00.000Z"),
"death" : ISODate("2011-12-24T05:00:00.000Z"),
"contribs" : [
"Lisp",
"Artificial Intelligence",
"ALGOL"
]
}
This JSON object is just an example, I can't know what a JSONObject contains since I import it. I don't have any information about the name of fields to use Gson/Jackson to deserialization.
Suppose I have a JSONObject myDocJson
that contains the previous JSON Object, I use an iterator:
Iterator<?> keys = myDocJson.keySet().iterator();
while(keys.hasNext()) {
System.out.println(keys.next());
}
And as a result I get:
name
birth
death
contribs
But for example I don't have name.first
and name.last
. So this iterator does not work with innested Object.
You are only printing the keys.
To get the values, try
JSONObject object = null; // your json object
for (Object key : object.keySet()) {
System.out.println(key + "=" + object.get(key)); // to get the value
}
EDIT
And for the objects inside of your JSONObject try
JSONObject object = null; // your json object
for (Object key : object.keySet()) {
System.out.println(key + "=" + object.get(key)); // to get the value
for (Object subKey : ((JSONObject) object.get(key)).keySet()) {
System.out.println(subKey + "=" + object.get(subKey));
}
}
I belive that you need know the json structure. If be necessary, iterate over the childrens.
Edit: I was wrong. This question can help you, see Sean Patrick Floyd's answer: JSON - Iterate through JSONArray
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.