jackson逆シーケンス化時間万能日付フォーマットマッチング統合

12507 ワード

jacksonのregisterModule機能を使用して、異なる日付タイプの逆シーケンス化器を登録し、様々なシーンの日付フォーマットマッチングをサポートし、タイプfastjson式の呼び出し方法をカプセル化します.
主入口類JSON:
package xxx.util;

import java.lang.reflect.Type;
import java.util.List;
import java.util.TimeZone;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import xxx.XxxRuntimeException;
import xxx.DateDeserializer;
import xxx.SqlDateDeserializer;
import xxx.TimestampDeserializer;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.type.TypeFactory;

/**
 * JSON   (  jackson  )
 * 
 * @author   
 * @since JDK1.8
 * @version 2020 6 8       
 */
public class JSON {
    
    /**
     *   
     */
    private final static Logger LOGGER = LoggerFactory.getLogger(JSON.class);
    
    /**
     *    
     */
    private static ObjectMapper MAPPER;
    
    static {
        MAPPER = new ObjectMapper();
        //           
        MAPPER.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        //         
        MAPPER.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        //           
        MAPPER.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true);
        //            
        // MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //               
        MAPPER.setTimeZone(TimeZone.getDefault());
        // null    json    
        MAPPER.setSerializationInclusion(Include.NON_NULL);
        
        //           
        SimpleModule module = new SimpleModule();
        module.addDeserializer(java.util.Date.class, new DateDeserializer());
        module.addDeserializer(java.sql.Date.class, new SqlDateDeserializer());
        module.addDeserializer(java.sql.Timestamp.class, new TimestampDeserializer());
        MAPPER.registerModule(module);
    }
    
    /**
     *     
     */
    private JSON() {
        
    }
    
    /**
     *  JSON            
     * 
     * @param      
     * @param content JSON     
     * @param clazz List       
     * @return List  
     */
    public static  List parseArray(String content, Class clazz) {
        try {
            return MAPPER.readValue(content, new TypeReference>() {
                //
            });
        } catch (Exception e) {
            LOGGER.error("JSON      :" + e.getMessage(), e);
            throw new XxxRuntimeException("JSON      :" + e.getMessage(), e);
        }
    }
    
    /**
     *  JSON            
     * 
     * @param content JSON     
     * @param valueType    
     * @param      
     * @return  JSON            
     */
    public static  T parseObject(String content, Class valueType) {
        try {
            return MAPPER.readValue(content, valueType);
        } catch (Exception e) {
            LOGGER.error("JSON      :" + e.getMessage(), e);
            throw new XxxRuntimeException("JSON      :" + e.getMessage(), e);
        }
    }
    
    /**
     *  JSON                
     * 
     * @param content JSON     
     * @param genericType     
     * @param      
     * @return  JSON            
     */
    public static  T parseObject(String content, Type genericType) {
        try {
            return MAPPER.readValue(content, TypeFactory.defaultInstance().constructType(genericType));
        } catch (Exception e) {
            LOGGER.error("JSON      :" + e.getMessage(), e);
            throw new XxxRuntimeException("JSON      :" + e.getMessage(), e);
        }
    }
    
    /**
     *  JSON            -      
     * 
     * @param      
     * @param content JSON     
     * @param valueTypeRef     
     * @return     
     */
    public static  T parseObject(String content, TypeReference valueTypeRef) {
        try {
            return MAPPER.readValue(content, valueTypeRef);
        } catch (Exception e) {
            LOGGER.error("JSON      :" + e.getMessage(), e);
            throw new XxxRuntimeException("JSON      :" + e.getMessage(), e);
        }
    }
    
    /**
     *       JSON   
     * 
     * @param object   
     * @return JSON   
     */
    public static String toJSONString(Object object) {
        try {
            return MAPPER.writeValueAsString(object);
        } catch (Exception e) {
            LOGGER.error("JSON     :" + e.getMessage(), e);
            throw new XxxRuntimeException("JSON     :" + e.getMessage(), e);
        }
    }
    
    /**
     *             
     * 
     * @param      
     * @param fromValue    
     * @param toValueTypeRef       
     * @return     
     */
    public static  T convertObject(Object fromValue, TypeReference toValueTypeRef) {
        return MAPPER.convertValue(fromValue, toValueTypeRef);
    }
    
    /**
     *             
     * 
     * @param      
     * @param fromValue    
     * @param toValueType     class  
     * @return     
     */
    public static  T convertObject(Object fromValue, Class toValueType) {
        return MAPPER.convertValue(fromValue, toValueType);
    }
    
    /**
     *   ObjectMapper  
     * 
     * @return   ObjectMapper  
     */
    public static ObjectMapper getMapper() {
        return MAPPER;
    }
    
}

 
カスタムDateDeserializer日付逆シーケンス化:
package xxx;

import java.io.IOException;
import java.util.Date;

import xxx.DatePatternUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

/**
 * java.util.Date        
 * 
 * @author   
 * @since JDK1.8
 * @version 2020 6 9       
 */
public class DateDeserializer extends StdDeserializer {
    
    /**
     *     
     *
     */
    public DateDeserializer() {
        this(null);
    }
    
    /**
     *     
     *
     * @param vc Class
     */
    public DateDeserializer(Class> vc) {
        super(vc);
    }
    
    /**
     * @see com.fasterxml.jackson.databind.JsonDeserializer#deserialize(com.fasterxml.jackson.core.JsonParser,
     *      com.fasterxml.jackson.databind.DeserializationContext)
     */
    @Override
    public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        return DatePatternUtil.getPatternDate(p.getValueAsString());
    }
}

ユニバーサル日付マッチDatePatternUtil:
package xxx.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *          
 * 
 * @author   
 * @since JDK1.7
 * @version 2019 5 15       
 */
public class DatePatternUtil {
    
    /**
     *     
     */
    private DatePatternUtil() {
        
    }
    
    /**     */
    private static final List patternList = new ArrayList(5);
    
    /**        */
    private static final Pattern PATTERN1 = Pattern.compile("\\d{4}");
    
    /**        */
    private static final Pattern PATTERN2 = Pattern.compile("\\d{4}-\\d{1,2}");
    
    /**        */
    private static final Pattern PATTERN3 = Pattern.compile("(\\d{4}\\-\\d{1,2}\\-\\d{1,2})");
    
    /**        */
    private static final Pattern PATTERN4 = Pattern.compile("(\\d{4}\\-\\d{1,2}\\-\\d{1,2} \\d{1,2}:\\d{1,2})");
    
    /**        */
    private static final Pattern PATTERN5 = Pattern.compile("\\d{4}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}:\\d{1,2}:\\d{1,2}");
    
    /**        */
    private static final Pattern PATTERN6 = Pattern
        .compile("\\d{4}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d+");
    
    /**        */
    private static final Pattern PATTERN7 = Pattern.compile("\\d{4}/\\d{1,2}/\\d{1,2}");
    
    /**        */
    private static final Pattern PATTERN8 = Pattern
        .compile("\\w{3}\\s\\w{3}\\s\\d{1,2}\\s\\d{4}\\s\\d{1,2}:\\d{1,2}:\\d{1,2}\\sGMT\\+0800");
    
    /**        */
    private static final Pattern PATTERN9 = Pattern.compile("\\d{4}\\d{1,2}");
    
    /**        */
    private static final Pattern PATTERN10 = Pattern.compile("(\\d{4}\\d{1,2}\\d{1,2})");
    
    /**     */
    private static final Map patternMap = new HashMap();
    
    static {
        patternMap.put(PATTERN1, "yyyy");
        patternMap.put(PATTERN2, "yyyy-MM");
        patternMap.put(PATTERN3, "yyyy-MM-dd");
        patternMap.put(PATTERN4, "yyyy-MM-dd HH:mm");
        patternMap.put(PATTERN5, "yyyy-MM-dd HH:mm:ss");
        patternMap.put(PATTERN6, "yyyy-MM-dd HH:mm:ss.SSS");
        patternMap.put(PATTERN7, "yyyy/MM/dd");
        patternMap.put(PATTERN8, "EEE MMM dd yyyy HH:mm:ss 'GMT+0800'");
        patternMap.put(PATTERN9, "yyyyMM");
        patternMap.put(PATTERN10, "yyyyMMdd");
        
        //   pattern
        patternList.add(PATTERN1);
        patternList.add(PATTERN2);
        patternList.add(PATTERN3);
        patternList.add(PATTERN4);
        patternList.add(PATTERN5);
        patternList.add(PATTERN6);
        patternList.add(PATTERN7);
        patternList.add(PATTERN8);
        patternList.add(PATTERN9);
        patternList.add(PATTERN10);
    }
    
    /**
     *                 
     * 
     * @param strDateValue          
     * @return Date
     */
    public static Date getPatternDate(String strDateValue) {
        String value = strDateValue;
        if (value == null || "".equals(value.trim()) || "null".equalsIgnoreCase(value.trim())) {
            return null;
        }
        //                ,            。
        if (value.indexOf('%') >= 0) {
            try {
                value = URLDecoder.decode(value, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                //
            }
        }
        
        String format = getMatchFormat(value);
        if (format == null) {
            //     8          ,          ,         Date,        
            Matcher matcher = Pattern.compile("[-]?\\d+").matcher(value);
            boolean isMatch = matcher.matches();
            if (isMatch) {
                return new Date(Long.valueOf(value));
            }
            throw new IllegalArgumentException("        :" + value);
        }
        
        if (format.indexOf("GMT") > 0) {
            SimpleDateFormat objSimpleFormat = new SimpleDateFormat(format, Locale.US);
            try {
                return objSimpleFormat.parse(value);
            } catch (ParseException e) {
                throw new IllegalArgumentException("        :" + value);
            }
        }
        
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            return sdf.parse(value);
        } catch (ParseException e) {
            throw new IllegalArgumentException("        :" + value);
        }
    }
    
    /**
     *           
     *
     * 
     * @param value   
     * @return   
     */
    private static String getMatchFormat(final String value) {
        Pattern pattern = null;
        for (Iterator iterator = patternList.iterator(); iterator.hasNext();) {
            pattern = iterator.next();
            Matcher matcher = pattern.matcher(value);
            boolean isMatch = matcher.matches();
            if (isMatch) {
                return patternMap.get(pattern);
            }
        }
        return null;
    }
    
}