fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4.  
  5. public static boolean isValidJson(Object input) {
  6. if (!(input instanceof Map)) return false;
  7. return checkMap((Map<?, ?>) input);
  8. }
  9.  
  10. private static boolean checkMap(Map<?, ?> map) {
  11. for (Map.Entry<?, ?> entry : map.entrySet()) {
  12. if (!(entry.getKey() instanceof String)) return false;
  13.  
  14. Object value = entry.getValue();
  15. if (value == null || value instanceof String || value instanceof Number || value instanceof Boolean) {
  16. continue;
  17. } else if (value instanceof Map) {
  18. if (!checkMap((Map<?, ?>) value)) return false;
  19. } else if (value instanceof List) {
  20. if (!checkList((List<?>) value)) return false;
  21. } else {
  22. return false;
  23. }
  24. }
  25. return true;
  26. }
  27.  
  28. private static boolean checkList(List<?> list) {
  29. for (Object item : list) {
  30. if (item == null || item instanceof String || item instanceof Number || item instanceof Boolean) {
  31. continue;
  32. } else if (item instanceof Map) {
  33. if (!checkMap((Map<?, ?>) item)) return false;
  34. } else if (item instanceof List) {
  35. if (!checkList((List<?>) item)) return false;
  36. } else {
  37. return false;
  38. }
  39. }
  40. return true;
  41. }
  42.  
  43. public static void main(String[] args) {
  44. // Valid
  45. Map<String, Object> valid = new HashMap<>();
  46. valid.put("user", Map.of("name", "A", "age", 30));
  47.  
  48. valid.put("tags", Arrays.asList("java", 123, true, null));
  49.  
  50. System.out.println(isValidJson(valid)); // true
  51.  
  52. // tidak valid key bukan String
  53. Map<Object, Object> invalid1 = new HashMap<>();
  54. invalid1.put(123, "abc");
  55. System.out.println(isValidJson(invalid1)); // false
  56.  
  57. // tidak valid ada tipe aneh (Date)
  58. Map<String, Object> invalid2 = new HashMap<>();
  59. invalid2.put("time", new Date());
  60. System.out.println(isValidJson(invalid2)); // false
  61. }
  62. }
  63.  
Success #stdin #stdout 0.12s 52720KB
stdin
Standard input is empty
stdout
true
false
false