All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.df.restypass.util.JsonTools Maven / Gradle / Ivy

There is a newer version: 1.5.1
Show newest version
package com.github.df.restypass.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.ParseException;
import java.util.Collection;
import java.util.Date;
import java.util.Map;

/**
 * JsonTools
 * copy from spring side < calvin >
 * author: fuliang
 * date: 2017/3/29
 */
@SuppressWarnings("unused")
public class JsonTools {

    private static Logger logger = LoggerFactory.getLogger(JsonTools.class);
    private static String SIMPLE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public static final JsonTools INSTANCE = new JsonTools();

    private ObjectMapper mapper;

    public JsonTools() {
        this(null);
    }

    public JsonTools(JsonInclude.Include include) {
        mapper = new ObjectMapper();
        // 设置输出时包含属性的风格
        if (include != null) {
            mapper.setSerializationInclusion(include);
        }
        // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

        SimpleModule javaTimeModule = new SimpleModule();
        javaTimeModule.addSerializer(Date.class, new JsonDateSerializer());
        javaTimeModule.addDeserializer(Date.class, new JsonDateDeserializer());
        mapper.registerModule(javaTimeModule);
    }

    /**
     * Date序列化
     */
    public static class JsonDateSerializer extends JsonSerializer {

        @Override
        public void serialize(Date date, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
            String formattedDate = DateFormatTools.formatDate(SIMPLE_FORMAT, date);
            gen.writeString(formattedDate);
        }
    }

    /**
     * Date反序列化
     */
    public static class JsonDateDeserializer extends JsonDeserializer {
        @Override
        public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            if (StringUtils.isEmpty(jp.getText())) {
                return null;
            }
            try {
                return DateFormatTools.pareDate(SIMPLE_FORMAT, jp.getText());
            } catch (ParseException e) {
                throw new IOException(e.getMessage());
            }

        }
    }

    /**
     * 创建只输出非Null的属性到Json字符串的Mapper.
     */
    public static JsonTools nonNullMapper() {
        return new JsonTools(JsonInclude.Include.NON_NULL);
    }

    /**
     * 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper.
     * 

* 注意,要小心使用, 特别留意empty的情况. */ public static JsonTools nonEmptyMapper() { return new JsonTools(JsonInclude.Include.NON_EMPTY); } /** * 默认的全部输出的Mapper, 区别于INSTANCE,可以做进一步的配置 */ public static JsonTools defaultMapper() { return new JsonTools(); } /** * Object可以是POJO,也可以是Collection或数组。 如果对象为Null, 返回"null". 如果集合为空集合, 返回"[]". */ public String toJson(Object object) { try { return mapper.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) * * @see #fromJson(String, JavaType) */ public T fromJson(String jsonString, Class clazz) { if (StringUtils.isEmpty(jsonString)) { return null; } try { return mapper.readValue(jsonString, clazz); } catch (IOException e) { logger.warn("parse json string error:" + jsonString, e); return null; } } /** * 反序列化复杂Collection如List, contructCollectionType()或contructMapType()构造类型, 然后调用本函数. */ public T fromJson(String jsonString, TypeReference typeReference) { if (StringUtils.isEmpty(jsonString)) { return null; } try { return (T) mapper.readValue(jsonString, typeReference); } catch (IOException e) { logger.warn("parse json string error:" + jsonString, e); return null; } } /** * 反序列化复杂Collection如List, contructCollectionType()或contructMapType()构造类型, 然后调用本函数. */ public T fromJson(String jsonString, JavaType javaType) { if (StringUtils.isEmpty(jsonString)) { return null; } try { return (T) mapper.readValue(jsonString, javaType); } catch (IOException e) { logger.warn("parse json string error:" + jsonString, e); return null; } } /** * 构造Collection类型. */ public JavaType buildCollectionType(Class collectionClass, Class elementClass) { return mapper.getTypeFactory().constructCollectionType(collectionClass, elementClass); } /** * 构造Map类型. */ public JavaType buildMapType(Class mapClass, Class keyClass, Class valueClass) { return mapper.getTypeFactory().constructMapType(mapClass, keyClass, valueClass); } /** * 当JSON里只含有Bean的部分属性時,更新一個已存在Bean,只覆盖該部分的属性. */ public void update(String jsonString, Object object) { try { mapper.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); } } /** * 輸出JSONP格式數據. */ public String toJsonP(String functionName, Object object) { return toJson(new JSONPObject(functionName, object)); } /** * 設定是否使用Enum的toString函數來讀寫Enum, 為False時時使用Enum的name()函數來讀寫Enum, 默認為False. 注意本函數一定要在Mapper創建後, 所有的讀寫動作之前調用. */ public void enableEnumUseToString() { mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); } /** * 取出Mapper做进一步的设置或使用其他序列化API. */ public ObjectMapper getMapper() { return mapper; } }





© 2015 - 2025 Weber Informatics LLC | Privacy Policy