fork download
  1. import java.lang.reflect.Array;
  2. import java.util.*;
  3.  
  4. class JsonStructureValidator {
  5.  
  6. public static boolean isValidJson(Object input) {
  7. Set<Object> seen = Collections.newSetFromMap(new IdentityHashMap<>());
  8. return isValidJsonImpl(input, seen);
  9. }
  10.  
  11. private static boolean isValidJsonImpl(Object input, Set<Object> seen) {
  12. if (input == null) return true;
  13.  
  14. if (isPrimitiveAllowed(input)) return true;
  15.  
  16. if (input instanceof Map) {
  17. if (!seen.add(input)) return false;
  18.  
  19. Map<?, ?> map = (Map<?, ?>) input;
  20. for (Map.Entry<?, ?> e : map.entrySet()) {
  21. Object key = e.getKey();
  22. Object value = e.getValue();
  23.  
  24. if (!(key instanceof String)) {
  25. seen.remove(input);
  26. return false;
  27. }
  28.  
  29. if (!isValidJsonImpl(value, seen)) {
  30. seen.remove(input);
  31. return false;
  32. }
  33. }
  34. seen.remove(input);
  35. return true;
  36. }
  37.  
  38. if (input instanceof List) {
  39. if (!seen.add(input)) return false;
  40.  
  41. List<?> list = (List<?>) input;
  42. for (Object item : list) {
  43. if (!isValidJsonImpl(item, seen)) {
  44. seen.remove(input);
  45. return false;
  46. }
  47. }
  48. seen.remove(input);
  49. return true;
  50. }
  51.  
  52. if (input.getClass().isArray()) {
  53. if (!seen.add(input)) return false;
  54.  
  55. int len = Array.getLength(input);
  56. for (int i = 0; i < len; i++) {
  57. Object elem = Array.get(input, i);
  58. if (!isValidJsonImpl(elem, seen)) {
  59. seen.remove(input);
  60. return false;
  61. }
  62. }
  63. seen.remove(input);
  64. return true;
  65. }
  66.  
  67. return false;
  68. }
  69.  
  70. private static boolean isPrimitiveAllowed(Object input) {
  71. return input instanceof String
  72. || input instanceof Number
  73. || input instanceof Boolean;
  74. }
  75.  
  76. public static void main(String[] args) {
  77. Map<String, Object> valid = Map.of("user", Map.of("name", "A", "age", 30));
  78. System.out.println(isValidJson(valid)); // true
  79.  
  80. Map<String, Object> m2 = new HashMap<>();
  81. m2.put("tags", List.of("x", "y"));
  82. m2.put("scores", new int[] {1, 2, 3});
  83. System.out.println(isValidJson(m2)); // true
  84.  
  85. Map<Object, Object> wrongKey = new HashMap<>();
  86. wrongKey.put(123, "numberAsKey");
  87. System.out.println(isValidJson(wrongKey)); // false
  88.  
  89. Map<String, Object> withSet = new HashMap<>();
  90. withSet.put("s", Set.of("a", "b"));
  91. System.out.println(isValidJson(withSet)); // false
  92.  
  93. }
  94. }
  95.  
Success #stdin #stdout 0.08s 54616KB
stdin
Standard input is empty
stdout
true
true
false
false