Skip to content

Commit 7e5865e

Browse files
author
jiachengzhuo
committed
Implement Milestone 4: toStream() with JSONNode support
1 parent a736292 commit 7e5865e

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

src/main/java/org/json/JSONObject.java

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
import java.util.*;
1818
import java.util.Map.Entry;
1919
import java.util.regex.Pattern;
20+
import java.util.stream.IntStream;
21+
import java.util.stream.Stream;
2022

2123
/**
2224
* A JSONObject is an unordered collection of name/value pairs. Its external
@@ -3030,4 +3032,64 @@ private static String removeLeadingZerosOfNumber(String value){
30303032
if (negativeFirstChar) {return "-0";}
30313033
return "0";
30323034
}
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+
}
30333095
}

0 commit comments

Comments
 (0)