The essential difference between Jackson's @ JsonFormat and @ DateTimeFormat

1. Problems

Two problems are often encountered in front and back-end interaction during development:

  • 1. When the back end returns data to the front end, the Date attribute in the moudel object needs to be formatted and displayed to the front end (for example, formatted as yyyy MM DD HH: mm: SS).
  • 2. When the front end passes parameters to the back-end interface, the formatted time string (for example: createTime="2020-11-29 20:10:11") needs to be converted into the Date attribute in the back-end moudel object.

There are two ways to solve this problem:

  • 1. Manual formatting: for example, each time the data returned to the front end uses SimpleDateFormat to convert the Date into a string in the specified format, and the same is true for the accepted parameters. This method requires manual conversion whenever there is an interface of Date type interaction, which is cumbersome and redundant.
  • 2. Use annotation: @ JsonFormat and @ DateTimeFormat are used in different ways.

2. Difference between @ jsonformat annotation and @ DateTimeFormat

  • (1) The @ jsonformat annotation is Jackson's annotation, and the default json parser of Spring MVC and Spring Boot is Jackson@ DateTimeFormat annotation is the annotation of spring.

  • (2) The @ datetimeformat annotation only receives and processes the time parameter conversion of the key value pair in the front-end form post request@ The JsonFormat annotation can only handle the time conversion in the standard post request (content type = Application / JSON).

(1)form form key value pair request

There are two types of form post requests: content type = Application / x-www-form-urlencoded and content type = multipart / form data. When the front end uses the form post request, the @ RequestBody annotation is not required on the interface parameters, and the parameters are directly obtained from the key/value of the form.

@RestController
public class LearnDataController{
    @PostMapping("/learn/data/get/userInfo")
    public void userInfo(UserInfo userInfo) throws Exception {
        System.out.println(userInfo);
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(userInfo);
        System.out.println(json);
    }
}
@Data
public class UserInfo implements Serializable {
    private Long id;
    private String name;
    private Integer age;
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date birthDate;
}

//Note: when making a form type post request, the back-end Controller interface does not need to add @ RequestBody annotation. The time attribute in the parameter UserInfo can only use @ DateTimeFormat to specify the received time format.

(2) post request in standard json format

When the front end sends a standard post request (i.e. content type = Application / JSON), the @ requestbody annotation needs to be added to the parameter to indicate that the parameter is obtained from the requestbody of http.

@RestController
public class LearnDataController{
    @PostMapping("/learn/data/get/userInfo")
    public void userInfo(@RequestBody UserInfo userInfo) throws Exception {
        System.out.println(userInfo);
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(userInfo);
        System.out.println(json);
    }
}
//When making a standard post request (content type = Application / JSON), you need to add @ RequestBody to get the parameters from the body. The time attribute in parameter UserInfo can only use @ JsonFormat to receive parameters with specified time format.
@Data
public class UserInfo implements Serializable {
    private Long id;
    private String name;
    private Integer age;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT + 8")
    private Date birthDate;
}

(3) Back end returns value to front end

When the back end passes the time value to the front end, you can only use @ JsonFormat to return the specified format characters to the front end, @ DateTimeFormat cannot determine the format of the return value. Because spring deserializes the Jackson framework used by default.

3. Summary

(1). Front end to back end
The key value pair (two form post requests) is passed from the front end, and the received time format is specified with @ DateTimeFormat.
The json string is sent from the current end, and the background receives it with @ ReuqestBody, and specifies the time format of the reception with @ JsonFormat.

(2). Back end to front end
The time value returned by the back end to the front end can only use @ JsonFormat to return the specified format characters to the front end, @ DateTimeFormat cannot determine the format of the return value.

(3).@JsonFormat is provided by jackson@ DateTimeFormat is provided by spring.

#(1) @ DateTimeFormat is the annotation of spring, which aims to specify the time format of receiving when the front-end form submits a post request.

#(2) There are two types of form post requests. When the parameters passed from the current end have time types, use @ DateTimeFormat to specify the time format received.
    1)Content-type=application/x-www-form-urlencoded It is the default submission type of the form, based on key/value Submitted to the server in the form of.
    2)Content-type=multipart/form-data It will process the data of the form into a message, with labels as units and separated by separators. You can upload both key value pairs and files.

Finally, I'd like to talk about something else. Today, I saw the entrepreneurs in Hurun's 100 rich list. Behind their worth of more than 100 billion, there are debts of 10 billion and 100 billion. For example, some time ago, ant financial services had a loan scale of 2 trillion, of which 98% were dry sons; For another example, in this year's real estate, no one has worked through three red lines. Basically, the larger the plate, the higher the debt. Sigh, if ordinary people like us want to realize the class jump of several generations, it is only possible to continuously increase leverage. Many people in this life, only this opportunity to buy a house can get the condition of leverage. However, when choosing down payment and mortgage, they lost this only opportunity.

                                                                                                                 

On the evening of November 29, 2020 in Beijing

Tags: Java JSON Spring jackson

Posted by Jezza on Thu, 05 May 2022 02:25:32 +0300