diff --git a/jee7/src/main/java/com/baeldung/json/PersonWriter.java b/jee7/src/main/java/com/baeldung/json/PersonWriter.java index f94c02d613..7b6f82e23b 100644 --- a/jee7/src/main/java/com/baeldung/json/PersonWriter.java +++ b/jee7/src/main/java/com/baeldung/json/PersonWriter.java @@ -1,5 +1,7 @@ package com.baeldung.json; +import javax.json.*; +import javax.json.stream.JsonGenerator; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; @@ -7,50 +9,42 @@ import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Map; -import javax.json.Json; -import javax.json.JsonArrayBuilder; -import javax.json.JsonObject; -import javax.json.JsonObjectBuilder; -import javax.json.JsonWriterFactory; -import javax.json.stream.JsonGenerator; - public class PersonWriter { private Person person; private SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); - + public PersonWriter(Person person) { this.person = person; } public String write() throws IOException { - JsonObjectBuilder objectBuilder = Json.createObjectBuilder() - .add("firstName", person.getFirstName()) - .add("lastName", person.getLastName()) - .add("birthdate", dateFormat.format(person.getBirthdate())); - - JsonArrayBuilder arrayBuilder = Json.createArrayBuilder(); - - for(String email : person.getEmails()) { - arrayBuilder.add(email); - } - + JsonObjectBuilder objectBuilder = Json + .createObjectBuilder() + .add("firstName", person.getFirstName()) + .add("lastName", person.getLastName()) + .add("birthdate", dateFormat.format(person.getBirthdate())); + + final JsonArrayBuilder arrayBuilder = Json.createArrayBuilder(); + + person.getEmails().forEach(arrayBuilder::add); + objectBuilder.add("emails", arrayBuilder); - + JsonObject jsonObject = objectBuilder.build(); - + JsonWriterFactory writerFactory = createWriterFactory(); - - String jsonString = writeToString(jsonObject, writerFactory); - - return jsonString; - + + return writeToString(jsonObject, writerFactory); + } private String writeToString(JsonObject jsonObject, JsonWriterFactory writerFactory) throws IOException { String jsonString; - try(Writer writer = new StringWriter()) { - writerFactory.createWriter(writer).write(jsonObject); + try (Writer writer = new StringWriter()) { + writerFactory + .createWriter(writer) + .write(jsonObject); jsonString = writer.toString(); } return jsonString; @@ -60,8 +54,7 @@ public class PersonWriter { Map config = new HashMap<>(); config.put(JsonGenerator.PRETTY_PRINTING, true); - - JsonWriterFactory writerFactory = Json.createWriterFactory(config); - return writerFactory; + + return Json.createWriterFactory(config); } }