javaspring-bootjacksonjsr310

jackson json date format convert


Please help to change date format.

**Source** json file

**Target** Employee Object

I need support for converting file json date to Object. from file

{
 "dateOfBirth": {
    "year": 1980,
    "month": "MAY",
    "monthValue": 5,
    "dayOfMonth": 4,
    "dayOfYear": 124,
    "dayOfWeek": "WEDNESDAY",
    "chronology": {
      "calendarType": "iso8601",
      "id": "ISO"
    },
    "era": "CE",
    "leapYear": false
  }
}

to Object

{"dateOfBirth": "1980-05-04"}

Object

public class Employee {   
    private LocalDate dateOfBirth;
    //setter
    //getter
}

Library "com.fasterxml.jackson.datatype:jackson-datatype-jsr310"

Date : java.time.LocalDate

My goal is to read json data from file and map it to object.


Solution

  • You can use custom deserializer.

    public class EmployeeBirthDateDeserializer extends StdDeserializer<LocalDate> {
    
      public EmployeeBirthDateDeserializer() {
        super(LocalDate.class);
      }
    
      @Override
      public LocalDate deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        JsonNode root = parser.getCodec().readTree(parser);
        return LocalDate.of(root.get("year").asInt(), root.get("monthValue").asInt(), root.get("dayOfMonth").asInt());
      }
    }
    

    Then apply it only to dateOfBirth field in Employee using @JsonDeserialize:

    public class Employee {
    
      @JsonDeserialize(using = EmployeeBirthDateDeserializer.class)
      private LocalDate dateOfBirth;
    
      //getters and setter
    }
    

    Test:

    public class Temp {
    
      public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        Employee employee = mapper.readValue(ClassLoader.getSystemResourceAsStream("strange-date.json"), Employee.class);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        System.out.println(formatter.format(employee.getDateOfBirth()));
      }
    }
    

    Prints: 1980-05-04.