1. import org.json.JSONArray;
  2. import org.json.JSONObject;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. public class JsonProcessor {
  6. public static List<String> processJson(String jsonString) {
  7. List<String> results = new ArrayList<>();
  8. try {
  9. JSONObject jsonObject = new JSONObject(jsonString);
  10. // Example: Accessing nested data with error handling
  11. String name = (String) jsonObject.get("person", "name"); // Default to "name" if "person" is missing
  12. if (name != null) {
  13. results.add("Name: " + name);
  14. } else {
  15. results.add("Name: Not found");
  16. }
  17. JSONObject personDetails = jsonObject.getJSONObject("person");
  18. String age = (String) personDetails.get("age"); //Default value if missing
  19. if (age != null) {
  20. results.add("Age: " + age);
  21. } else {
  22. results.add("Age: Not found");
  23. }
  24. // Example: Handling array of objects
  25. JSONArray items = jsonObject.getJSONArray("items");
  26. if (items != null) {
  27. for (int i = 0; i < items.length(); i++) {
  28. JSONObject item = items.getJSONObject(i);
  29. String itemName = item.getString("name");
  30. if (itemName != null) {
  31. results.add("Item " + (i + 1) + ": " + itemName);
  32. } else {
  33. results.add("Item " + (i + 1) + ": Name not found");
  34. }
  35. }
  36. } else {
  37. results.add("Items: Not found");
  38. }
  39. } catch (Exception e) {
  40. // Graceful failure handling
  41. System.err.println("Error processing JSON: " + e.getMessage());
  42. results.add("Error: JSON processing failed - " + e.getMessage());
  43. }
  44. return results;
  45. }
  46. public static void main(String[] args) {
  47. String json = "{\"person\": {\"name\": \"Alice\", \"age\": \"30\"}, \"items\": [{\"name\": \"Apple\"}, {\"name\": \"Banana\"}]}";
  48. List<String> output = processJson(json);
  49. for (String line : output) {
  50. System.out.println(line);
  51. }
  52. // Example with missing data and invalid JSON
  53. String json2 = "{\"person\": {\"age\": \"30\"}, \"items\": [{\"name\": \"Apple\"}, ]}"; //Missing name in last item
  54. List<String> output2 = processJson(json2);
  55. for (String line : output2) {
  56. System.out.println(line);
  57. }
  58. String invalidJson = "{\"person\": {\"name\": \"Alice\", \"age\": \"30\""; //invalid JSON
  59. List<String> output3 = processJson(invalidJson);
  60. for (String line : output3) {
  61. System.out.println(line);
  62. }
  63. }
  64. }

Add your comment