Search code examples
javajsonobjectmapper

ObjectMapper returns null value on date field


My data is as below and saved in test folder with name risk.json

[{
    "Risk": "BN",
    "Classification": null,
    "LastDefaultDate": "1915-04-14 00:00:00"
  }]

I have RiskClass defined as below

@Data
@JsonIgnoreProperties({"document"})
public class RiskClass implements KeyedObject {

    String risk;
    String classification;
    Date lastDefaultDate;

    @Override
    public String getKey() {
        return risk;
    }
}

In my data prepare class i am trying to populate one of the map by doing below

List<RiskClass> rList = ObjectUtils.jsonStringToObjList(readFileAsString("test", "risk.json"), RiskClass.class);
Map<String, RiskClass> riskMapLocal = new HashMap<>();
for (RiskClass rMap : rList) {
    riskMapLocal.put(rMap.getRisk(), rMap);
}

now when i try to print riskMapLocal, under lastDefaultDate i get null value.


Solution

  • Add an annotation over your property lastDefaultDate:

        @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
        LocalDateTime lastDefaultDate;
    

    Also change type Date to LocalDateTime as Date type is outdated (pun intended). For more details look at this question and its best answer: Spring Data JPA - ZonedDateTime format for json serialization