Skip to content

Commit 7405b00

Browse files
committed
JacksonCollectors.toJsonNode implementation
signature rename to toArrayNode
1 parent 04a6719 commit 7405b00

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.fasterxml.jackson.databind.util;
2+
3+
import com.fasterxml.jackson.databind.JsonNode;
4+
import com.fasterxml.jackson.databind.node.ArrayNode;
5+
import com.fasterxml.jackson.databind.node.JsonNodeCreator;
6+
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
7+
import java.util.stream.Collector;
8+
9+
/**
10+
* Utility class that provides custom {@link Collector} implementations to support Stream operations.
11+
* <p>
12+
* This class is not meant to be instantiated and serves only as a utility class.
13+
* </p>
14+
*
15+
* @since 2.18
16+
*/
17+
public abstract class JacksonCollectors {
18+
/**
19+
* Creates a {@link Collector} that collects {@link JsonNode} elements into an {@link ArrayNode}.
20+
* <p>
21+
* This method uses a {@link JsonNodeFactory} to create an empty {@link ArrayNode} and then adds each
22+
* {@link JsonNode} to it.
23+
* </p>
24+
*
25+
* @return a {@link Collector} that collects {@link JsonNode} elements into an {@link ArrayNode}
26+
*/
27+
public static Collector<JsonNode, ArrayNode, ArrayNode> toJsonArray() {
28+
return toJsonArray(JsonNodeFactory.instance);
29+
}
30+
31+
public static Collector<JsonNode, ArrayNode, ArrayNode> toJsonArray(JsonNodeCreator nodeCreator) {
32+
return Collector.of(
33+
nodeCreator::arrayNode, // supplier
34+
ArrayNode::add, // accumulator
35+
ArrayNode::addAll // combiner
36+
);
37+
}
38+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.fasterxml.jackson.databind.util;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertFalse;
5+
6+
import com.fasterxml.jackson.databind.JsonNode;
7+
import com.fasterxml.jackson.databind.ObjectMapper;
8+
import com.fasterxml.jackson.databind.node.ObjectNode;
9+
import java.util.stream.IntStream;
10+
import org.junit.jupiter.api.Test;
11+
12+
public class JacksonCollectorsTest {
13+
14+
@Test
15+
public void testToJsonArray()
16+
{
17+
final ObjectMapper objectMapper = new ObjectMapper();
18+
19+
final JsonNode jsonNodeResult = IntStream.range(0, 10)
20+
.mapToObj(i -> {
21+
ObjectNode objectNode = objectMapper.createObjectNode();
22+
objectNode.put("testString", "example");
23+
objectNode.put("testNumber", i);
24+
objectNode.put("testBoolean", true);
25+
26+
return objectNode;
27+
})
28+
.collect(JacksonCollectors.toJsonArray());
29+
30+
assertEquals(10, jsonNodeResult.size());
31+
jsonNodeResult.forEach(jsonNode -> assertFalse(jsonNode.isEmpty()));
32+
}
33+
}

0 commit comments

Comments
 (0)