spring controller 파라미터 분석 및 Jackson 데이터 직렬 화 및 반 직렬 화 방안

2840 단어 자바
package com.linkmcn.mcn.web.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.linkmcn.mcn.common.core.config.LocalDateTimeJsonDeserializer;
import com.linkmcn.mcn.common.core.config.LocalDateTimeJsonSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;


@Configuration
public class ConverterConfig {

    /**
     *     LocalDateTime   
     * 

* localDateTime */ @Bean public Converter longLocalDateTimeConverter() { return new Converter() { @Override public LocalDateTime convert(String str) { if (StringUtils.hasText(str)) { long timestamp = Long.parseLong(str); return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault()); } return null; } }; } /** * @param * @Description: JackSon LocalDateTime * @return: com.fasterxml.jackson.databind.ObjectMapper * @Author: Mr.Zhong * @Date: 2019-08-02 11:11 */ @Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); JavaTimeModule timeModule = new JavaTimeModule(); timeModule.addSerializer(LocalDateTime.class, new LocalDateTimeJsonSerializer()); // JSON timeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeJsonDeserializer());// JSON

mapper.registerModule(timeModule); return mapper; }
/**
 * @program: mcn
 * @description:    JSON          
 * @author: Mr.Zhong
 * @create: 2019-08-01 20:42
 **/
@JsonComponent  //         JsonSerializer
public class LocalDateTimeJsonDeserializer extends JsonDeserializer{
    @Override
    public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) {

        try {
            if (StringUtils.hasText(jsonParser.getText())) {
                return LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.valueOf(jsonParser.getText())), ZoneId.systemDefault());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
}

좋은 웹페이지 즐겨찾기