import org.json.JSONArray;
import org.json.JSONObject;
public class ApiFormatter {
public static void formatApiResponse(String jsonString) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
// Print the entire JSON object
System.out.println("--- Raw JSON ---");
System.out.println(jsonObject.toString(2)); // Use 2 spaces for indentation
System.out.println("------------------");
// Iterate through the JSON object and print key-value pairs
for (String key : jsonObject.keySet()) {
Object value = jsonObject.get(key);
System.out.printf("Key: %s\n", key); // Print the key
if (value instanceof JSONObject) {
System.out.println(" Nested JSON:");
System.out.println(formatApiResponse(value.toString())); // Recursive call for nested objects
} else if (value instanceof JSONArray) {
System.out.println(" JSON Array:");
JSONArray jsonArray = (JSONArray) value;
for (int i = 0; i < jsonArray.length(); i++) {
Object arrayValue = jsonArray.get(i);
System.out.printf(" Element %d: %s\n", i, arrayValue);
if (arrayValue instanceof JSONObject) {
System.out.println(" Nested JSON:");
System.out.println(formatApiResponse(arrayValue.toString()));
} else if (arrayValue instanceof JSONArray) {
System.out.println(" Nested Array:");
System.out.println(formatApiResponse(arrayValue.toString()));
} else {
System.out.printf(" Value: %s\n", arrayValue);
}
}
} else {
System.out.printf(" Value: %s\n", value); // Print primitive values
}
}
} catch (Exception e) {
System.err.println("Error processing JSON: " + e.getMessage());
}
}
public static void main(String[] args) {
// Example usage:
String jsonResponse = "{\"name\": \"John Doe\", \"age\": 30, \"city\": \"New York\", \"address\": {\"street\": \"123 Main St\", \"zip\": \"10001\"}, \"hobbies\": [\"reading\", \"hiking\"]}";
formatApiResponse(jsonResponse);
}
}
Add your comment