简单封装Jackson,实现JSON String to Java Object的Mapper,记录日期序列化与反序列化

public class JsonMapper extends ObjectMapper {

    private static final long serialVersionUID = 1L;

    private static Logger logger = LoggerFactory.getLogger(JsonMapper.class);

    private static JsonMapper mapper;

    private static final List formarts = new ArrayList(4);
    static{
        formarts.add("yyyy-MM");
        formarts.add("yyyy-MM-dd");
        formarts.add("yyyy-MM-dd hh:mm");
        formarts.add("yyyy-MM-dd hh:mm:ss");
    }
    public JsonMapper() {
        this(Include.ALWAYS);
    }

    public JsonMapper(Include include) {
        // 设置输出时包含属性的风格
        if (include != null) {
            this.setSerializationInclusion(include);
        }
        // 允许单引号、允许不带引号的字段名称
        this.enableSimple();
        // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
        this.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        // 空值处理为空串
//        this.getSerializerProvider().setNullValueSerializer(new JsonSerializer() {
//            @Override
//            public void serialize(Object value, JsonGenerator jgen,
//                                  SerializerProvider provider) throws IOException,
//                    JsonProcessingException {
//                jgen.writeString("");
//            }
//        });
        // 进行HTML解码。
        this.registerModule(new SimpleModule().addSerializer(String.class, new JsonSerializer() {
            @Override
            public void serialize(String value, JsonGenerator jgen,
                                  SerializerProvider provider) throws IOException,
                    JsonProcessingException {
                jgen.writeString(StringEscapeUtils.unescapeHtml4(value));
            }
        }));

        // 设置时区
        this.setTimeZone(TimeZone.getDefault());//getTimeZone("GMT+8:00")

        this.registerModule(new SimpleModule().addSerializer(Date.class, new JsonSerializer() {
            @Override
            public void serialize(Date value, JsonGenerator jgen,
                                  SerializerProvider provider) throws IOException,
                    JsonProcessingException {

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                jgen.writeString(sdf.format(value));
            }
        }));
        this.registerModule(new SimpleModule().addDeserializer(Date.class, new JsonDeserializer() {
            @Override
            public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
                String source = p.getText().trim();
                if(source.matches("^\\d{4}-\\d{1,2}$")){
                    return parseDate(source, formarts.get(0));
                }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")){
                    return parseDate(source, formarts.get(1));
                }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")){
                    return parseDate(source, formarts.get(2));
                }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")){
                    return parseDate(source, formarts.get(3));
                }else if(source.matches("^\\d{13}$")){//毫秒
                    return new Date(Long.parseLong(source));
                }else if(source.matches("^\\d{10}$")){//秒
                    return new Date(Long.parseLong(source) * 1000);
                }else {
                    throw new IllegalArgumentException("Invalid Date value '" + source + "'");
                }
            }
            public  Date parseDate(String dateStr, String format) {
                Date date = null;
                try {
                    DateFormat dateFormat = new SimpleDateFormat(format);
                    date = (Date) dateFormat.parse(dateStr);
                } catch (Exception e) {
                }
                return date;
            }
        }));
    }

    /**
     * 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper,建议在外部接口中使用.
     *
     * @return JsonMapper 生成实例
     */
    public static JsonMapper getInstance() {
        if (mapper == null) {
            mapper = new JsonMapper().enableSimple();
        }
        return mapper;
    }

    /**
     * 创建只输出初始值被改变的属性到Json字符串的Mapper, 最节约的存储方式,建议在内部接口中使用。
     *
     * @return JsonMapper 生成实例
     */
    public static JsonMapper nonDefaultMapper() {
        if (mapper == null) {
            mapper = new JsonMapper(Include.NON_DEFAULT);
        }
        return mapper;
    }

    /**
     * Object可以是POJO,也可以是Collection或数组。
     * 如果对象为Null, 返回"null".
     * 如果集合为空集合, 返回"[]".
     *
     * @return String json字符格式
     */
    public String toJson(Object object) {
        try {
            return this.writeValueAsString(object);
        } catch (IOException e) {
            logger.warn("write to json string error:" + object, e);
            return null;
        }
    }

    /**
     * 反序列化POJO或简单Collection如List.
     * 如果JSON字符串为Null或"null"字符串, 返回Null.
     * 如果JSON字符串为"[]", 返回空集合.
     * 

* 如需反序列化复杂Collection如List, 请使用fromJson(String,JavaType) * * @return 反序列化后的对象 * @see #fromJson(String, JavaType) */ public T fromJson(String jsonString, Class clazz) { if (StringUtils.isEmpty(jsonString)) { return null; } try { return this.readValue(jsonString, clazz); } catch (IOException e) { logger.warn("parse json string error:" + jsonString, e); return null; } } /** * 反序列化复杂Collection如List, 先使用函數createCollectionType构造类型,然后调用本函数. * * @return 反序列化后的对象 * @see #createCollectionType(Class, Class...) */ public T fromJson(String jsonString, JavaType javaType) { if (StringUtils.isEmpty(jsonString)) { return null; } try { return (T) this.readValue(jsonString, javaType); } catch (IOException e) { logger.warn("parse json string error:" + jsonString, e); return null; } } /** * 構造泛型的Collection Type如: * ArrayList, 则调用constructCollectionType(ArrayList.class,MyBean.class) * HashMap, 则调用(HashMap.class,String.class, MyBean.class) * * @return 集合类型 */ public JavaType createCollectionType(Class collectionClass, Class... elementClasses) { return this.getTypeFactory().constructParametricType(collectionClass, elementClasses); } /** * 當JSON裡只含有Bean的部分屬性時,更新一個已存在Bean,只覆蓋該部分的屬性. * * @return 更新后集合 */ @SuppressWarnings("unchecked") public T update(String jsonString, T object) { try { return (T) this.readerForUpdating(object).readValue(jsonString); } catch (JsonProcessingException e) { logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e); } catch (IOException e) { logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e); } return null; } /** * 輸出JSONP格式數據. */ public String toJsonP(String functionName, Object object) { return toJson(new JSONPObject(functionName, object)); } /** * 設定是否使用Enum的toString函數來讀寫Enum, * 為False時時使用Enum的name()函數來讀寫Enum, 默認為False. * 注意本函數一定要在Mapper創建後, 所有的讀寫動作之前調用. */ public JsonMapper enableEnumUseToString() { this.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); this.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); return this; } /** * 允许单引号 * 允许不带引号的字段名称 */ public JsonMapper enableSimple() { this.configure(Feature.ALLOW_SINGLE_QUOTES, true); this.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); return this; } /** * 取出Mapper做进一步的设置或使用其他序列化API. */ public ObjectMapper getMapper() { return this; } /** * 对象转换为JSON字符串 * * @param object * @return */ public static String toJsonString(Object object) { return JsonMapper.getInstance().toJson(object); } /** * JSON字符串转换为对象 * * @param jsonString * @param clazz * @return */ public static T fromJsonString(String jsonString, Class clazz) { return JsonMapper.getInstance().fromJson(jsonString, clazz); } /** * JSON字符串转为集合对象 * @param jsonString * @param collectionClass * @param elementClasses * @return */ public static T fromJsonString(String jsonString,Class collectionClass, Class... elementClasses) { return JsonMapper.getInstance().fromJson(jsonString, JsonMapper.getInstance().createCollectionType(collectionClass,elementClasses)); } }

你可能感兴趣的:(简单封装Jackson,实现JSON String to Java Object的Mapper,记录日期序列化与反序列化)