@JsonDeserialize collection parsing instance

There are many blogs about the basic usage of @JsonDeserialize and @JsonSerialize:

https://blog.csdn.net/yage124/article/details/107321339/ icon-default.png?t=M85Bhttps://blog.csdn.net/yage124/article/details/107321339/ https://www.h5w3.com/249702.html icon-default.png?t=M85Bhttps ://www.h5w3.com/249702.html The above are two common deserialization.

The current situation is:

The front end passes a collection of strings, and the back end receives the classes in the collection:

The front end passes parameters:

{
  "applyTimeSection": ["2020-02-19 08:11:11","2020-02-19 08:20:11"]
}

 The backend receives:

private List<Date> applyTimeSection;

Through some basic usage, we know that using @JsonDeserialize to deserialize requires implementing a custom deserialization class.

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 将List<Sting> 转换为 List<Date>
 */
public class Strings2Dates extends JsonDeserializer<List<Date>> {
    @Override
    public List<Date> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        if (ObjectUtils.isEmpty(p)) {
            return Collections.emptyList();
        }
//        对于集合类型getText()方法是不行的
//        p.getText()
//        此处是重点:VO对应的属性是什么类型,此处的参数就什么类型
        List<String> list = p.readValueAs(List.class);
        List<Date> dates = new ArrayList<>();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for (String date : list) {
            LocalDateTime parse = LocalDateTime.parse(date, dateTimeFormatter);
            Instant instant = parse.toInstant(ZoneOffset.ofHours(8));
            dates.add(Date.from(instant));
        }
        return dates;
    }
}

After defining the deserialization class, we can add annotations to the setter method of the property corresponding to VO.

  @JsonDeserialize(using = Strings2Dates.class)
    public void setApplyTimeSelection(List<Date> applyTimeSelection) {
        this.applyTimeSelection = applyTimeSelection;
    }

Guess you like

Origin blog.csdn.net/kanyun123/article/details/126956203
Recommended