Flattening Nested JSON in Java
1 min readFeb 7, 2023
To flatten a nested JSON in Java, you can use a library such as Jackson or Gson to parse the JSON and convert it into a flat structure, such as a Map or a List of key-value pairs. You can then iterate over the keys and values in the flat structure to access the values in the nested JSON. Here’s an example using Jackson:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Map;
public class FlattenJson {
public static void main(String[] args) throws IOException {
String json = "{\"name\":\"John\",\"age\":30,\"address\":{\"street\":\"123 Main St\",\"city\":\"San Francisco\"}}";
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(json);
flatten(root, "");
}
private static void flatten(JsonNode node, String prefix) {
if (node.isObject()) {
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
flatten(field.getValue(), prefix + field.getKey() + ".");
}
} else if (node.isArray()) {
for (int i = 0; i < node.size(); i++) {
flatten(node.get(i), prefix + "[" + i + "].");
}
} else {
System.out.println(prefix + ": " + node.asText());
}
}
}
This will output:
name: John
age: 30
address.street: 123 Main St
address.city: San Francisco