Skip to content

Commit aa87a22

Browse files
authored
[bug fix] #464 fix missing comma in toJson for nested arrays (#465)
With arrays of arrays, the toJson content is missing a comma between the nested arrays. The fix is in JGenerator.startArray() to add the missing comma prefix when the prior written "value" ended in a OP_END.
1 parent d26caad commit aa87a22

File tree

4 files changed

+48
-0
lines changed

4 files changed

+48
-0
lines changed
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package org.example.customer.nesting;
2+
3+
import io.avaje.jsonb.Json;
4+
5+
import java.util.List;
6+
7+
@Json
8+
public record MyNestedList(List<List<Long>> nestedInts) {
9+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package org.example.customer.nesting;
2+
3+
import io.avaje.jsonb.JsonType;
4+
import io.avaje.jsonb.Jsonb;
5+
import org.junit.jupiter.api.Test;
6+
7+
import java.util.List;
8+
9+
import static org.assertj.core.api.Assertions.assertThat;
10+
11+
class MyNestedListTest {
12+
13+
JsonType<MyNestedList> jsonb = Jsonb.instance().type(MyNestedList.class);
14+
15+
@Test
16+
void toJson_fromJson() {
17+
var nested = new MyNestedList(List.of(List.of(1L, 2L, 3L), List.of(8L, 9L)));
18+
String asJson = jsonb.toJson(nested);
19+
assertThat(asJson).isEqualTo("{\"nestedInts\":[[1,2,3],[8,9]]}");
20+
21+
MyNestedList myNestedList = jsonb.fromJson(asJson);
22+
assertThat(myNestedList.nestedInts()).hasSize(2);
23+
assertThat(myNestedList.nestedInts().get(0)).contains(1L, 2L, 3L);
24+
assertThat(myNestedList.nestedInts().get(1)).contains(8L, 9L);
25+
}
26+
}

json-core/src/main/java/io/avaje/json/stream/core/JGenerator.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -546,6 +546,9 @@ public void endObject() {
546546

547547
@Override
548548
public void startArray() {
549+
if (lastOp == OP_END) {
550+
writeByte(COMMA);
551+
}
549552
writeByte(ARRAY_START);
550553
lastOp = OP_START;
551554
if (pretty) {

json-node/src/test/java/io/avaje/json/node/JsonArrayTest.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,4 +145,14 @@ void toPlain() {
145145
assertThat(plain.get(1)).isEqualTo(Map.of("b", 42));
146146
}
147147

148+
@Test
149+
void toJson_nested_array() {
150+
JsonArray top = JsonArray.create()
151+
.add(JsonArray.create().add("a"))
152+
.add(JsonArray.create().add("b"));
153+
154+
String asJson = mapper.toJson(top);
155+
assertThat(asJson).isEqualTo("[[\"a\"],[\"b\"]]");
156+
}
157+
148158
}

0 commit comments

Comments
 (0)