package com.zm.order.tool.server.utils;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;

/**
 * json转换工具类
 *
 * @author qixiaodong
 */
public class JacksonUtils {

    private static final Log log = LogFactory.getLog(JacksonUtils.class);

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    static {
        // 设置序列化时忽略值为null的元素
        OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * bean转为string类型的json
     *
     * <p>
     *
     * </p>
     *
     * @param obj obj
     *
     * @return String
     */
    public static String toJsonString(Object obj) {
        if (obj == null) {
            return null;
        }
        try {
            return OBJECT_MAPPER.writeValueAsString(obj);
        } catch (Exception e) {
            log.error("bean 转换成 json失败！", e);
        }
        return null;
    }

    public static JsonNode parseJson(String json) {
        if (json == null){
            return null;
        }
        try {
            return OBJECT_MAPPER.readTree(json);
        }catch (Exception e){
            return null;
        }
    }

    public static <T> T getObjectFromJsonString(String jsonString, Class<T> cls) {
        if (jsonString == null) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(jsonString, cls);
        } catch (Exception e) {
            log.error("json转换成 bean失败！", e);
        }
        return null;
    }

    public static <T> List<T> stringToList(String json, Class<T> object) {
        if (json == null) {
            return null;
        }
        try {
            CollectionType listType = OBJECT_MAPPER.getTypeFactory().constructCollectionType(ArrayList.class, object);
            return OBJECT_MAPPER.readValue(json, listType);
        } catch (Exception e) {
            log.error("json转换成 bean失败！", e);
        }
        return null;
    }

}
