Refactor PersonWriter
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,13 +9,6 @@ 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;
@@ -24,16 +19,15 @@ public class PersonWriter {
}
public String write() throws IOException {
- JsonObjectBuilder objectBuilder = Json.createObjectBuilder()
+ JsonObjectBuilder objectBuilder = Json
+ .createObjectBuilder()
.add("firstName", person.getFirstName())
.add("lastName", person.getLastName())
.add("birthdate", dateFormat.format(person.getBirthdate()));
- JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
+ final JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
- for(String email : person.getEmails()) {
- arrayBuilder.add(email);
- }
+ person.getEmails().forEach(arrayBuilder::add);
objectBuilder.add("emails", arrayBuilder);
@@ -41,16 +35,16 @@ public class PersonWriter {
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);
+ writerFactory
+ .createWriter(writer)
+ .write(jsonObject);
jsonString = writer.toString();
}
return jsonString;
@@ -61,7 +55,6 @@ public class PersonWriter {
config.put(JsonGenerator.PRETTY_PRINTING, true);
- JsonWriterFactory writerFactory = Json.createWriterFactory(config);
- return writerFactory;
+ return Json.createWriterFactory(config);
}
}
