BAEL-6293: Add builder pattern for ObjectMapper creation (#14112)

Co-authored-by: Tapan Avasthi <tavasthi@Tapans-MacBook-Air.local>
This commit is contained in:
Tapan Avasthi 2023-05-27 19:14:01 +05:30 committed by GitHub
parent 498cc8aa98
commit 668b8f0b77
2 changed files with 89 additions and 0 deletions

View File

@ -0,0 +1,45 @@
package com.baeldung.jackson.objectmapper;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.util.TimeZone;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class ObjectMapperBuilder {
private boolean enableIndentation;
private boolean preserveOrder;
private DateFormat dateFormat;
public ObjectMapperBuilder enableIndentation() {
this.enableIndentation = true;
return this;
}
public ObjectMapperBuilder dateFormat() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm a z");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(ZoneId.of("Asia/Kolkata")));
this.dateFormat = simpleDateFormat;
return this;
}
public ObjectMapperBuilder preserveOrder(boolean order) {
this.preserveOrder = order;
return this;
}
public ObjectMapper build() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, this.enableIndentation);
objectMapper.setDateFormat(this.dateFormat);
if (this.preserveOrder) {
objectMapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
}
return objectMapper;
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.jackson.objectmapper;
import java.util.Date;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import com.baeldung.jackson.objectmapper.dto.Car;
import com.baeldung.jackson.objectmapper.dto.Request;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ObjectMapperBuilderUnitTest {
ObjectMapper mapper = new ObjectMapperBuilder()
.enableIndentation()
.dateFormat()
.preserveOrder(true)
.build();
Car givenCar = new Car("White", "Sedan");
String givenCarJsonStr = "{ \"color\" : \"White\", \"type\" : \"Sedan\" }";
@Test
public void whenReadCarJsonStr_thenReturnCarObjectCorrectly() throws JsonProcessingException {
Car actual = mapper.readValue(givenCarJsonStr, Car.class);
Assertions.assertEquals("White", actual.getColor());
Assertions.assertEquals("Sedan", actual.getType());
}
@Test
public void whenWriteRequestObject_thenReturnRequestJsonStrCorrectly() throws JsonProcessingException {
Request request = new Request();
request.setCar(givenCar);
Date date = new Date(1684909857000L);
request.setDatePurchased(date);
String actual = mapper.writeValueAsString(request);
String expected = "{\n" + " \"car\" : {\n" + " \"color\" : \"White\",\n" +
" \"type\" : \"Sedan\"\n" + " },\n" + " \"datePurchased\" : \"2023-05-24 12:00 PM IST\"\n" +
"}";
Assertions.assertEquals(expected, actual);
}
}