1. import org.json.JSONArray;
  2. import org.json.JSONObject;
  3. public class ApiFormatter {
  4. public static void formatApiResponse(String jsonString) {
  5. try {
  6. JSONObject jsonObject = new JSONObject(jsonString);
  7. // Print the entire JSON object
  8. System.out.println("--- Raw JSON ---");
  9. System.out.println(jsonObject.toString(2)); // Use 2 spaces for indentation
  10. System.out.println("------------------");
  11. // Iterate through the JSON object and print key-value pairs
  12. for (String key : jsonObject.keySet()) {
  13. Object value = jsonObject.get(key);
  14. System.out.printf("Key: %s\n", key); // Print the key
  15. if (value instanceof JSONObject) {
  16. System.out.println(" Nested JSON:");
  17. System.out.println(formatApiResponse(value.toString())); // Recursive call for nested objects
  18. } else if (value instanceof JSONArray) {
  19. System.out.println(" JSON Array:");
  20. JSONArray jsonArray = (JSONArray) value;
  21. for (int i = 0; i < jsonArray.length(); i++) {
  22. Object arrayValue = jsonArray.get(i);
  23. System.out.printf(" Element %d: %s\n", i, arrayValue);
  24. if (arrayValue instanceof JSONObject) {
  25. System.out.println(" Nested JSON:");
  26. System.out.println(formatApiResponse(arrayValue.toString()));
  27. } else if (arrayValue instanceof JSONArray) {
  28. System.out.println(" Nested Array:");
  29. System.out.println(formatApiResponse(arrayValue.toString()));
  30. } else {
  31. System.out.printf(" Value: %s\n", arrayValue);
  32. }
  33. }
  34. } else {
  35. System.out.printf(" Value: %s\n", value); // Print primitive values
  36. }
  37. }
  38. } catch (Exception e) {
  39. System.err.println("Error processing JSON: " + e.getMessage());
  40. }
  41. }
  42. public static void main(String[] args) {
  43. // Example usage:
  44. String jsonResponse = "{\"name\": \"John Doe\", \"age\": 30, \"city\": \"New York\", \"address\": {\"street\": \"123 Main St\", \"zip\": \"10001\"}, \"hobbies\": [\"reading\", \"hiking\"]}";
  45. formatApiResponse(jsonResponse);
  46. }
  47. }

Add your comment