I have the below json sample and i would like to get the object names dynamically without passing as string.
{
"John": {
"Age": "22",
"status": "married"
},
"Ross": {
"Age": "34",
"status": "divorced"
}
}
I want to get keys John and Ross. I tried with
JSONObject parse = JSON.parseObject("");
for (Map.Entry<String, Object> entry : parse.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
but the above code gives all the keys inside. i only want the parent keys.
you can change parse.entrySet()
to parse.keySet()
to get the desire result.
JSONObject parse = JSON.parseObject("");
for (Map.Entry<String, Object> entry : parse.keySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
Assuming the use of fastjson. Use keySet
instead.
JSONObject parse = JSON.parseObject("");
for (String entry : parse.keySet()) {
System.out.println(entry);
}
This will print:
John
Ross
Tested with:
String s = "{\"John\":{\"Age\":\"22\",\"status\":\"married\"},\"Ross\":{\"Age\":\"34\",\"status\":\"divorced\"}}";
JSONObject parse = JSON.parseObject(s);
for (String entry : parse.keySet()) {
System.out.println(entry);
}
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.