On 10/23/13 1:18 PM, Hildeberto Mendonça wrote:
> Hello,
>
> I'm creating some Json content using the Object Model API and I
> realized that the sequence of creating JsonObjectBuilder and
> JsonArrayBuilder actually interferes in the final result. The
> following code won't include the categories in the resulting Json:
> List<CategoryMenu> 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 fix the problem, I have to move the highlighted line to after the
> iteration:
> List<CategoryMenu> 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"}]}
> In my humble opinion it should work in both cases because it gives
> more flexibility to the programmer. Is it supposed to work like that
> or is it an issue?
I don't consider it as an issue. What you are suggesting is a lazy
construction of JsonObject/JsonArray from the associated builders when
the final build happens. This may be ok for one level, but if the
constructed JsonObject is big tree, then one has to walk down the tree
and build those objects from the associated builders.
Jitu
>
> Regards,
>
> Hildeberto