BAEL-5191-JsonNode-Get-All-Keys-From-A-Json-Structure (#11451)

* BAEL-5191-JsonNode-Get-All-Keys-From-A-Json-Structure

* Added test cases for GetAllKeysFromJSON class methods

* Updated test class name
This commit is contained in:
priya-soni 2021-11-19 03:34:38 +05:30 committed by GitHub
parent b8861e8ea3
commit d26a604c20
2 changed files with 228 additions and 0 deletions

View File

@ -0,0 +1,172 @@
package com.baeldung.jackson.jsonnode;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
public class GetAllKeysFromJSON {
public static List<String> getKeysInJsonUsingMaps(String json, ObjectMapper mapper) {
List<String> keys = new ArrayList<>();
try {
Map<String, Object> jsonElements = mapper.readValue(json, new TypeReference<Map<String, Object>>() {
});
getAllKeys(jsonElements, keys);
return keys;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return keys;
}
public static void getAllKeys(Map<String, Object> jsonElements, List<String> keys) {
jsonElements.entrySet()
.forEach(entry -> {
keys.add(entry.getKey());
if (entry.getValue() instanceof Map) {
Map<String, Object> map = (Map<String, Object>) entry.getValue();
getAllKeys(map, keys);
} else if (entry.getValue() instanceof List) {
List<?> list = (List<?>) entry.getValue();
list.forEach(listEntry -> {
if (listEntry instanceof Map) {
Map<String, Object> map = (Map<String, Object>) listEntry;
getAllKeys(map, keys);
}
});
}
});
}
public static List<String> getKeysInJsonUsingJsonNodeFieldNames(String json, ObjectMapper mapper) {
List<String> keys = new ArrayList<>();
try {
JsonNode jsonNode = mapper.readTree(json);
Iterator<String> iterator = jsonNode.fieldNames();
iterator.forEachRemaining(e -> keys.add(e));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return keys;
}
public static List<String> getAllKeysInJsonUsingJsonNodeFieldNames(String json, ObjectMapper mapper) {
List<String> keys = new ArrayList<>();
try {
JsonNode jsonNode = mapper.readTree(json);
getAllKeysUsingJsonNodeFieldNames(jsonNode, keys);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return keys;
}
public static List<String> getAllKeysInJsonUsingJsonNodeFields(String json, ObjectMapper mapper) {
List<String> keys = new ArrayList<>();
try {
JsonNode jsonNode = mapper.readTree(json);
getAllKeysUsingJsonNodeFields(jsonNode, keys);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return keys;
}
public static void getAllKeysUsingJsonNodeFields(JsonNode jsonNode, List<String> keys) {
if (jsonNode.isObject()) {
Iterator<Entry<String, JsonNode>> fields = jsonNode.fields();
fields.forEachRemaining(field -> {
keys.add(field.getKey());
getAllKeysUsingJsonNodeFieldNames((JsonNode) field.getValue(), keys);
});
} else if (jsonNode.isArray()) {
ArrayNode arrayField = (ArrayNode) jsonNode;
arrayField.forEach(node -> {
getAllKeysUsingJsonNodeFieldNames(node, keys);
});
}
}
public static void getAllKeysUsingJsonNodeFieldNames(JsonNode jsonNode, List<String> keys) {
if (jsonNode.isObject()) {
Iterator<String> fieldNames = jsonNode.fieldNames();
fieldNames.forEachRemaining(fieldName -> {
keys.add(fieldName);
getAllKeysUsingJsonNodeFieldNames(jsonNode.get(fieldName), keys);
});
} else if (jsonNode.isArray()) {
ArrayNode arrayField = (ArrayNode) jsonNode;
arrayField.forEach(node -> {
getAllKeysUsingJsonNodeFieldNames(node, keys);
});
}
}
public static List<String> getKeysInJsonUsingJsonParser(String json, ObjectMapper mapper) {
List<String> keys = new ArrayList<>();
try {
JsonNode jsonNode = mapper.readTree(json);
JsonParser jsonParser = jsonNode.traverse();
while (!jsonParser.isClosed()) {
if (jsonParser.nextToken() == JsonToken.FIELD_NAME) {
keys.add((jsonParser.getCurrentName()));
}
}
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return keys;
}
public static List<String> getKeysInJsonUsingJsonParser(String json) {
List<String> keys = new ArrayList<>();
try {
JsonFactory factory = new JsonFactory();
JsonParser jsonParser = factory.createParser(json);
while (!jsonParser.isClosed()) {
if (jsonParser.nextToken() == JsonToken.FIELD_NAME) {
keys.add((jsonParser.getCurrentName()));
}
}
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return keys;
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.jackson.jsonnode;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
public class GetAllKeysFromJSONUnitTest {
private static String json = "{\r\n" + " \"Name\":\"Craig\",\r\n" + " \"Age\":10,\r\n" + " \"BookInterests\":[\r\n" + " {\r\n" + " \"Book\":\"The Kite Runner\",\r\n" + " \"Author\":\"Khaled Hosseini\"\r\n" + " },\r\n"
+ " {\r\n" + " \"Book\":\"Harry Potter\",\r\n" + " \"Author\":\"J. K. Rowling\"\r\n" + " }\r\n" + " ],\r\n" + " \"FoodInterests\":{\r\n" + " \"Breakfast\":[\r\n" + " {\r\n"
+ " \"Bread\":\"Whole wheat\",\r\n" + " \"Beverage\":\"Fruit juice\"\r\n" + " },\r\n" + " {\r\n" + " \"Sandwich\":\"Vegetable Sandwich\",\r\n" + " \"Beverage\":\"Coffee\"\r\n"
+ " }\r\n" + " ]\r\n" + " }\r\n" + "}";
private static ObjectMapper mapper = new ObjectMapper();
// Top level keys : [Name, Age, BookInterests, FoodInterests]
// All keys: [Name, Age, BookInterests, Book, Author, Book, Author, FoodInterests, Breakfast, Bread, Beverage, Sandwich, Beverage]
@Test
public void givenAJsonNode_whenUsingFieldNamesMethod_thenWeGetTopFieldNames() {
List<String> keys = GetAllKeysFromJSON.getKeysInJsonUsingJsonNodeFieldNames(json, mapper);
assertEquals(4, keys.size());
}
@Test
public void givenAJsonNode_whenUsingFieldNamesMethodForAllNodes_thenWeGetAllFieldNames() {
List<String> keys = GetAllKeysFromJSON.getAllKeysInJsonUsingJsonNodeFieldNames(json, mapper);
assertEquals(13, keys.size());
}
@Test
public void givenAJsonNode_whenUsingFieldsMethod_thenWeGetAllFieldNames() {
List<String> keys = GetAllKeysFromJSON.getAllKeysInJsonUsingJsonNodeFields(json, mapper);
assertEquals(13, keys.size());
}
@Test
public void givenAJsonNode_whenUsingJsonParserMethod_thenWeGetAllFieldNames() {
List<String> keys = GetAllKeysFromJSON.getKeysInJsonUsingJsonParser(json, mapper);
assertEquals(13, keys.size());
keys = GetAllKeysFromJSON.getKeysInJsonUsingJsonParser(json);
assertEquals(13, keys.size());
}
@Test
public void givenAJsonNode_whenUsingMaps_thenWeGetAllFieldNames() {
List<String> keys = GetAllKeysFromJSON.getKeysInJsonUsingMaps(json, mapper);
assertEquals(13, keys.size());
}
}