How to get all keys from a JSON-Object as a String array in Java
JSONObject implements the Map interface, so you can use the same way you'd use for Map to generate the list of keys. In particular, you can use the .keySet()
or .entrySet()
method.
For example (adapted from here):
JSONObject jsonObj = ...;
List<String> l = new ArrayList<String>(jsonObj.keySet());
Java - Extract the keys from JSON object in to a string whose values are true
The trick is walking the JSON tree and examining each node to determine if it is a BooleanNode or not.
This code will produce a List of node names that are of BooleanNode type AND have a true value:
@Test
public void test4() throws JsonProcessingException, IOException {
// https://stackoverflow.com/questions/69224118/java-extract-the-keys-from-json-object-in-to-a-string-whose-values-are-true
final ObjectMapper mapper = new ObjectMapper();
final InputStream jsonStream = getClass().getClassLoader().getResourceAsStream("test4.json");
final JsonNode root = mapper.readTree(jsonStream);
final List<String> nodes = new ArrayList<>();
walkJsonTree("root", root, nodes);
System.out.println(nodes);
}
private void walkJsonTree(final String name, final JsonNode node, final List<String> trueNodes) {
if (node.isObject()) {
final ObjectNode n = (ObjectNode) node;
final Iterator<String> it = n.fieldNames();
while (it.hasNext()) {
final String fn = it.next();
walkJsonTree(fn, n.get(fn), trueNodes);
}
} else if (node.isArray()) {
final ArrayNode n = (ArrayNode) node;
final Iterator<JsonNode> it = n.iterator();
while (it.hasNext()) {
walkJsonTree("array", it.next(), trueNodes);
}
} else if (node.isBoolean()) {
final BooleanNode n = (BooleanNode) node;
if (n.booleanValue()) {
trueNodes.add(name);
}
}
}
Get child key and values from JSON array: Java
Your problem is not related to Java, you just forgot a step.
String currentParentKeyProperties =
fieldsObject.optString(currentParentKey);
is not correct, what you want is to get a JSONObject.
How to get values of keys of inside array in json array
The problem is in this statement bindings
is a JsonArray
, get it as JsonArray
directly
JsonArray array = entry.getValue().getAsJsonObject().getAsJsonArray("bindings");
Solution
for(Map.Entry<String, JsonElement> entry : results.entrySet()) {
JsonArray array = entry.getValue().getAsJsonArray();
for (JsonElement jsonElement : array) {
for (Map.Entry<String, JsonElement> entry1 : jsonElement.getAsJsonObject().entrySet()) {
System.out.println("Key = " + entry1.getKey() + " Value = " + entry1.getValue() );
}
}
Extracting Keys from a JSONObject using keySet()
The javadoc says:
public interface JsonObject
extends JsonStructure, Map<String,JsonValue>
So, a JSONObject is a Map whose keys are of type String
, and whose values are of type JSONValue
.
And the javadoc of Map<K, V>.keySet()
says:
Set<K> keySet()
Returns a Set view of the keys contained in this map
So, what JSONObject.keySet()
returns is a Set<String>
(which is quite logical, since keys of JSON objects are strings).
So all that you want is:
Set<String> keys = posts.keySet();
Related Topics
How to Use Variables Declared in Another Class
Find Difference Between Two Strings
How to Find Distinct Rows With Field in List Using JPA and Spring
How to Scroll Scrollbar Horizontally Which Is Inside a Window Using Java
How to Force a Method to Throw an Exception in Junit Testing
Java.Sql.Sqlexception: Access Denied for User 'Root'@'Localhost' (Using Password: Yes)
Re-Prompt User After Invalid Input in Java
How to Enable Request Scope in Async Task Executor
How to Multiply a and B With My Recursive Method
Getting 400 for Spring Resttemplate Post
How to Know If All the Variables in a Class Are Null
Java Spring: Best Way to Convert a File to a Multipartfile
How to Get All Keys from a Json-Object as a String Array in Java
How to Get the Average of a 2D Array
Java 8 Streams - How to Merge Elements from the List With the Same Fields to One Element and Sum Up
Regex to Match Substring After Nth Occurence of Pipe Character
Mapstruct: Map List of Objects, When Object Is Mapped from Two Objects