java8-localDateTime等序列化和反序列化

2019-01-25  本文已影响10人  BenjaminCool

SimpleDateFormat

https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

How to parse/format dates with LocalDateTime? (Java 8)

How to parse/format dates with LocalDateTime? (Java 8)

localDateTime等序列化

https://stackoverflow.com/questions/39192945/serialize-java-8-localdate-as-yyyy-mm-dd-with-gson

localDateTime等反序列化

https://stackoverflow.com/questions/8650913/gson-deserializer-for-java-util-date


package com.tianli.sdb.service.utils;

import com.google.gson.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


public class GsonDateTimeBuilder {

    private static final Logger LOGGER = LoggerFactory.getLogger(GsonDateTimeBuilder.class);

    static List<SimpleDateFormat> localDateTimePatterns = new ArrayList<>(Arrays.asList(
            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"),
            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"),
            new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"),
            new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
    ));

    static List<SimpleDateFormat> localDatePatterns = new ArrayList<>(Arrays.asList(
            new SimpleDateFormat("yyyy-MM-dd")
    ));


    static JsonDeserializer<LocalDateTime> deser_localDateTime = new JsonDeserializer<LocalDateTime>() {
        @Override
        public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            LocalDateTime ldt = null;

            for (SimpleDateFormat pattern : localDateTimePatterns) {
                try {

                    String ldtStr = json.getAsJsonPrimitive().getAsString();
//                    LOGGER.debug("localdatetime " + ldtStr);

                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern.toPattern());
                    ldt = LocalDateTime.parse(ldtStr, formatter);

                    break;
                } catch (Throwable t) {
                    // Loop on
                }
            }

            return ldt;
        }
    };

    static JsonDeserializer<LocalDate> deser_localDate = new JsonDeserializer<LocalDate>() {
        @Override
        public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            LocalDate ld = null;

            for (SimpleDateFormat pattern : localDatePatterns) {
                try {

                    String ldStr = json.getAsJsonPrimitive().getAsString();

//                    LOGGER.debug("localdate " + ldStr);

                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern.toPattern());

                    ld = LocalDate.parse(ldStr, formatter);

                    break;
                } catch (Throwable t) {
                    // Loop on
                }
            }

            return ld;
        }
    };

    static JsonSerializer<LocalDateTime> ser_localDateTime = new JsonSerializer<LocalDateTime>() {
        @Override
        public JsonElement serialize(LocalDateTime src, Type typeOfSrc, JsonSerializationContext context) {

            //        return new JsonPrimitive(date.format(DateTimeFormatter.ISO_LOCAL_DATE)); // "yyyy-mm-dd"

            String ldtStr = "";

            if (src != null) {
                ldtStr = src.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
            }

            return new JsonPrimitive(ldtStr);
        }
    };


    static JsonSerializer<LocalDate> ser_localDate = new JsonSerializer<LocalDate>() {
        @Override
        public JsonElement serialize(LocalDate src, Type typeOfSrc, JsonSerializationContext context) {
            String ldStr = "";

            if (src != null) {

                ldStr = src.format(DateTimeFormatter.ISO_LOCAL_DATE);
            }
            return new JsonPrimitive(ldStr);
        }
    };

    static public GsonBuilder build() {
        return new GsonBuilder()
                .registerTypeAdapter(LocalDateTime.class, deser_localDateTime)
                .registerTypeAdapter(LocalDate.class, deser_localDate)
                .registerTypeAdapter(LocalDateTime.class, ser_localDateTime)
                .registerTypeAdapter(LocalDate.class, ser_localDate);

    }

}



上一篇 下一篇

猜你喜欢

热点阅读