|
17 | 17 | import java.util.*; |
18 | 18 | import java.util.Map.Entry; |
19 | 19 | import java.util.regex.Pattern; |
| 20 | +import java.util.stream.IntStream; |
| 21 | +import java.util.stream.Stream; |
20 | 22 |
|
21 | 23 | /** |
22 | 24 | * A JSONObject is an unordered collection of name/value pairs. Its external |
@@ -3030,4 +3032,64 @@ private static String removeLeadingZerosOfNumber(String value){ |
3030 | 3032 | if (negativeFirstChar) {return "-0";} |
3031 | 3033 | return "0"; |
3032 | 3034 | } |
| 3035 | + |
| 3036 | + // ---------------------------- Milestone 4 ------------------------------ |
| 3037 | + |
| 3038 | + /** |
| 3039 | + * Represents a node in the JSON object tree, with path and value. |
| 3040 | + */ |
| 3041 | + public static class JSONNode { |
| 3042 | + private final String path; |
| 3043 | + private final Object value; |
| 3044 | + |
| 3045 | + public JSONNode(String path, Object value) { |
| 3046 | + this.path = path; |
| 3047 | + this.value = value; |
| 3048 | + } |
| 3049 | + |
| 3050 | + public String getPath() { |
| 3051 | + return path; |
| 3052 | + } |
| 3053 | + |
| 3054 | + public Object getValue() { |
| 3055 | + return value; |
| 3056 | + } |
| 3057 | + |
| 3058 | + @Override |
| 3059 | + public String toString() { |
| 3060 | + return "JSONNode{path='" + path + "', value=" + value + '}'; |
| 3061 | + } |
| 3062 | + } |
| 3063 | + |
| 3064 | + /** |
| 3065 | + * Convert this JSONObject into a stream of JSONNode, allowing chained operations. |
| 3066 | + * @return Stream of JSONNode objects (each has a full path and a value) |
| 3067 | + */ |
| 3068 | + public Stream<JSONNode> toStream() { |
| 3069 | + return toStream("", this); |
| 3070 | + } |
| 3071 | + |
| 3072 | + /** |
| 3073 | + * Recursive helper method to flatten JSONObject/JSONArray into JSONNode stream. |
| 3074 | + */ |
| 3075 | + private Stream<JSONNode> toStream(String path, Object value) { |
| 3076 | + if (value instanceof JSONObject) { |
| 3077 | + JSONObject obj = (JSONObject) value; |
| 3078 | + return obj.keySet().stream() |
| 3079 | + .flatMap(key -> { |
| 3080 | + String newPath = path.isEmpty() ? "/" + key : path + "/" + key; |
| 3081 | + return toStream(newPath, obj.get(key)); |
| 3082 | + }); |
| 3083 | + } else if (value instanceof JSONArray) { |
| 3084 | + JSONArray array = (JSONArray) value; |
| 3085 | + return IntStream.range(0, array.length()) |
| 3086 | + .boxed() |
| 3087 | + .flatMap(i -> { |
| 3088 | + String newPath = path + "[" + i + "]"; |
| 3089 | + return toStream(newPath, array.get(i)); |
| 3090 | + }); |
| 3091 | + } else { |
| 3092 | + return Stream.of(new JSONNode(path, value)); |
| 3093 | + } |
| 3094 | + } |
3033 | 3095 | } |
0 commit comments