Home > database >  ObjectMapper returns null value on date field
ObjectMapper returns null value on date field

Time:01-23

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.

CodePudding user response:

Property names in json start with uppercase - Risk, etc. Fields in POJO start with lowercase - risk, so they can't be matched automatically. You can either:

  1. Change them in json to be lowercase
  2. Use annotation JsonProperty on the fields to specify the name of the property to match for this field.
public class RiskClass {

  @JsonProperty("Risk")
  String risk;
}

CodePudding user response:

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

  • Related