Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions README-M4.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Milestone 4 – Stream support for **JSONObject**

## What is Added

| Item | Description |
|------|-------------|
| `JSONObject.JSONNode` | Immutable leaf wrapper containing an absolute `path` and its `value`. |
| `Stream<JSONNode> JSONObject.toStream()` | Depth-first, **lazy** flattening of any `JSONObject/JSONArray` into a `Stream`. Only leaf nodes are emitted (low memory footprint). |

Path conventions
* Object keys: `/parent/child`
* Array items: `/array[0]/child`

---

## Run the test class
```bash
mvn -Dtest=org.json.junit.milestone4.tests.JSONObjectStreamTest test
62 changes: 62 additions & 0 deletions src/main/java/org/json/JSONObject.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
* A JSONObject is an unordered collection of name/value pairs. Its external
Expand Down Expand Up @@ -3030,4 +3032,64 @@ private static String removeLeadingZerosOfNumber(String value){
if (negativeFirstChar) {return "-0";}
return "0";
}

// ---------------------------- Milestone 4 ------------------------------

/**
* Represents a node in the JSON object tree, with path and value.
*/
public static class JSONNode {
private final String path;
private final Object value;

public JSONNode(String path, Object value) {
this.path = path;
this.value = value;
}

public String getPath() {
return path;
}

public Object getValue() {
return value;
}

@Override
public String toString() {
return "JSONNode{path='" + path + "', value=" + value + '}';
}
}

/**
* Convert this JSONObject into a stream of JSONNode, allowing chained operations.
* @return Stream of JSONNode objects (each has a full path and a value)
*/
public Stream<JSONNode> toStream() {
return toStream("", this);
}

/**
* Recursive helper method to flatten JSONObject/JSONArray into JSONNode stream.
*/
private Stream<JSONNode> toStream(String path, Object value) {
if (value instanceof JSONObject) {
JSONObject obj = (JSONObject) value;
return obj.keySet().stream()
.flatMap(key -> {
String newPath = path.isEmpty() ? "/" + key : path + "/" + key;
return toStream(newPath, obj.get(key));
});
} else if (value instanceof JSONArray) {
JSONArray array = (JSONArray) value;
return IntStream.range(0, array.length())
.boxed()
.flatMap(i -> {
String newPath = path + "[" + i + "]";
return toStream(newPath, array.get(i));
});
} else {
return Stream.of(new JSONNode(path, value));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package org.json.junit.milestone4.tests;

import org.json.JSONObject;
import org.json.JSONObject.JSONNode;
import org.json.XML;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
import java.util.Scanner;
import java.util.stream.Collectors;

import static org.junit.Assert.*;

/**
* Unit tests for the JSONObject.toStream() extension (Milestone 4) – JUnit 4 / Java 8.
*/
public class JSONObjectStreamTest {

private static JSONObject catalog;

@BeforeClass
public static void loadXml() throws Exception {
try (InputStream in = JSONObjectStreamTest.class.getResourceAsStream("/books.xml")) {
assertNotNull("books.xml must be on the class-path (src/test/resources)", in);

String xml;
try (Scanner scanner = new Scanner(in, StandardCharsets.UTF_8.name())) {
scanner.useDelimiter("\\A");
xml = scanner.hasNext() ? scanner.next() : "";
}

catalog = XML.toJSONObject(xml);
}
}

@Test
public void extractTitles() {
List<String> titles = catalog.toStream()
.filter(n -> n.getPath().endsWith("/title"))
.map(n -> n.getValue().toString())
.collect(Collectors.toList());

assertEquals(12, titles.size());
assertTrue(titles.contains("XML Developer's Guide"));
assertTrue(titles.contains("Visual Studio 7: A Comprehensive Guide"));
}

@Test
public void findExactPath() {
String wantedPath = "/catalog/book[0]/author";
Optional<JSONNode> node = catalog.toStream()
.filter(n -> n.getPath().equals(wantedPath))
.findFirst();

assertTrue(node.isPresent());
assertEquals("Gambardella, Matthew", node.get().getValue());
}

@Test
public void filterCheapBooks() {
List<JSONNode> cheapPrices = catalog.toStream()
.filter(n -> n.getPath().endsWith("/price"))
.filter(n -> Double.parseDouble(n.getValue().toString()) < 10.0)
.collect(Collectors.toList());

assertEquals(8, cheapPrices.size());
assertTrue(cheapPrices.stream()
.allMatch(n -> Double.parseDouble(n.getValue().toString()) < 10.0));
}
}
Loading