eclipse-ee4j / eclipse-ee4j/parsson

Sequence of adding a JsonArrayBuilder into a JsonObjectBuilder interferes in the final result

Open
#6 7 comments 0 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
17
Forks
25
PR merge metrics
No merged PRs in 30d

Description

While creating some Json content using the Object Model API, I realised that the sequence of adding a JsonArrayBuilder into a JsonObjectBuilder interferes in the final result. The following code won't include the categories in the resulting Json because the line, indicated with an arrow, adds the JsonArrayBuilder to the JsonObjectBuilder before JsonArrayBuilder is loaded with data :

```
List categories = categoryMenuBean.findCategoriesByMenu(menu);
JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
JsonArrayBuilder arrayBuilderCategories = Json.createArrayBuilder();

objectBuilder.add("categories", arrayBuilderCategories); // <--
for(CategoryMenu category: categories) {
arrayBuilderCategories.add(Json.createObjectBuilder()
.add("id", category.getId())
.add("name", category.getName()));
}

JsonObject model = objectBuilder.build();
StringWriter strWriter = new StringWriter();
try (JsonWriter jsonWriter = Json.createWriter(strWriter)) {
jsonWriter.writeObject(model);
}

System.out.println(strWriter.toString()); // output = []
```

To work around with the problem, I had to move that highlighted line to after the iteration:

```
List categories = categoryMenuBean.findCategoriesByMenu(menu);
JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
JsonArrayBuilder arrayBuilderCategories = Json.createArrayBuilder();

for(CategoryMenu category: categories) {
arrayBuilderCategories.add(Json.createObjectBuilder()
.add("id", category.getId())
.add("name", category.getName()));
}

objectBuilder.add("categories", arrayBuilderCategories); // <--
JsonObject model = objectBuilder.build();
StringWriter strWriter = new StringWriter();
try (JsonWriter jsonWriter = Json.createWriter(strWriter)) {
jsonWriter.writeObject(model);
}
System.out.println(strWriter.toString()); // output = {"categories":[{"id":1,"name":"Plat du Jour"},{"id":2,"name":"Permanent"}]}
```

Apparently, the build is performed right away, while data is added to those builder objects. In fact, it should be built only when the method build() is finally invoked. In both examples, it always happen when all data is added to the builders and it is time to build the final JsonObject model. Therefore, both examples above should work normally.
#### Environment
JDK 1.7, Glassfish 3.1.2.2, Jersey 1.8
#### Affected Versions
[1.0.3]

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.