Custom parsing of spring boot front and back separate Instant timestamps

In the spring boot project, the front end and the back end specify the transfer time using timestamp (precision ms)

@Data
public class Incident {
    @ApiModelProperty(value = "fault ID", example = "1")
    private Integer id;
    @ApiModelProperty(value = "Fault generation time", allowEmptyValue = true)
    private Instant createdTime;
    @ApiModelProperty(value = "Recovery time", allowEmptyValue = true)
    private Instant recoveryTime;
}

The above is a brief entity class definition

    @Transactional(rollbackFor = Exception.class)
    @PostMapping(path = "/incident")
    public void AddIncident(@Valid @RequestBody Incident incident) {

        incident.setBusinessId(0);
        if (1 != incidentService.addIncident(incident)) {
            throw new Exception("...");
        }
    }

During actual use, it is found that the createdTime and recoveryTime values in Incident are incorrect
Troubleshooting, the front end after removing the time stamp three bits (that is, ms number), the time is basically the same
Therefore, it can be determined that SpringBoot uses Second to convert the Instant

So add custom parsing for Instant type transformation (SpringBoot uses com.fasterxml.jackson to parse data)

public class InstantJacksonDeserialize extends JsonDeserializer<Instant> {
    @Override
    public Instant deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        String text = jsonParser.getText();
        Long aLong = Long.valueOf(text);
        Instant res = Instant.ofEpochMilli(aLong);
        return res;
    }
}

Add corresponding notes to the properties related to Instant. The code is as follows:

@Data
public class Incident {
    @ApiModelProperty(value = "fault ID", example = "1")
    private Integer id;
    @JsonDeserialize(using = InstantJacksonDeserialize.class)
    @ApiModelProperty(value = "Fault generation time", allowEmptyValue = true)
    private Instant createdTime;
    @JsonDeserialize(using = InstantJacksonDeserialize.class)
    @ApiModelProperty(value = "Recovery time", allowEmptyValue = true)
    private Instant recoveryTime;
}

After the annotation is added, the Instant object can be parsed according to the ms precision

PS:
If you think my article is helpful to you, you can scan the code to get the red bag, thank you!

Tags: Java SpringBoot Spring

Posted on Wed, 04 Dec 2019 05:37:26 -0500 by burgessm