Skip to content

Commit e9d656d

Browse files
authored
Merge pull request #26 from litetex/shorthand-jsonarray-to-jsonobject-stream-method
Added ``JsonArray#streamAs`` shortcut methods
2 parents f2bd866 + 0e64c2b commit e9d656d

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@
33
This is a fork of [nanojson](https://github.com/mmastrac/nanojson) for use by NewPipe(Extractor). It has the following changes:
44

55
- It returns an empty `JsonObject` or `JsonArray` by default instead of `null`, preventing `NullPointerException`s.
6-
- It accepts JS-like JSON, such as `{ this: 'is', an: 'example' }`.
6+
- It accepts JS-like JSON, such as `{ this: 'is', an: 'example' }`.
7+
- Added ``JsonArray#streamAs`` and ``JsonArray#streamAsJsonObjects`` shortcut methods.

src/main/java/com/grack/nanojson/JsonArray.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import java.util.ArrayList;
1919
import java.util.Arrays;
2020
import java.util.Collection;
21+
import java.util.stream.Stream;
2122

2223
/**
2324
* Extends an {@link ArrayList} with helper methods to determine the underlying JSON type of the list element.
@@ -253,4 +254,20 @@ public boolean isNumber(int key) {
253254
public boolean isString(int key) {
254255
return get(key) instanceof String;
255256
}
257+
258+
/**
259+
* Shortcut method to create a stream with only objects of these classes.
260+
*/
261+
public <T> Stream<T> streamAs(Class<T> clazz) {
262+
return stream()
263+
.filter(clazz::isInstance)
264+
.map(clazz::cast);
265+
}
266+
267+
/**
268+
* Shortcut method to create a stream that only contains {@link JsonObject JsonObjects}.
269+
*/
270+
public Stream<JsonObject> streamAsJsonObjects() {
271+
return streamAs(JsonObject.class);
272+
}
256273
}

0 commit comments

Comments
 (0)