Skip to content

Commit

Permalink
🐛 Fix BsonUtils.toJson() for empty arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
ujibang committed Dec 19, 2023
1 parent d90a980 commit d57642f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
8 changes: 4 additions & 4 deletions commons/src/main/java/org/restheart/utils/BsonUtils.java
Expand Up @@ -672,10 +672,8 @@ public static String toJson(BsonValue bson) {

/**
* @param bson either a BsonDocument or a BsonArray
* @param mode
* @param mode the JsonMode
* @return the minified string representation of the bson value
* @throws IllegalArgumentException if bson is not a BsonDocument or a
* BsonArray
*/
public static String toJson(BsonValue bson, JsonMode mode) {
if (bson == null) {
Expand All @@ -700,7 +698,9 @@ public static String toJson(BsonValue bson, JsonMode mode) {

sb.append("[");
bson.asArray().stream().map(e -> toJson(e)).map(e -> minify(e)).forEach(e -> sb.append(e).append(","));
sb.deleteCharAt(sb.length()-1); // remove last comma
if (sb.length() > 1) {
sb.deleteCharAt(sb.length()-1); // remove last comma
}
sb.append("]");

return sb.toString();
Expand Down
10 changes: 10 additions & 0 deletions commons/src/test/java/org/restheart/utils/BsonUtilsTest.java
Expand Up @@ -1000,4 +1000,14 @@ public void testXPathGet() {
assertFalse(BsonUtils.get(doc, "array[100].idx").isPresent());
assertFalse(BsonUtils.get(doc, "not.exists").isPresent());
}


@Test
public void testToJsonEmptyArray() {
var expected = "[]";

var actual = BsonUtils.toJson(new BsonArray());

assertEquals(expected, actual);
}
}

0 comments on commit d57642f

Please sign in to comment.