package com.shkj.wms.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lch
 */
public class JsonUtil {
    public static ObjectMapper MAPPER = new ObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).setSerializationInclusion(JsonInclude.Include.NON_NULL);

    /**
     * 将 JSON 字符串转化为map
     */
    public static <T> Map<String, Object> JsonStrToMapObject(String json) {
        Map<String, Object> map = new HashMap<>();
        try {
            map = MAPPER.readValue(json, Map.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return map;
    }

    /**
     * 将 JSON 字符串转化为map
     */
    public static <T> Map<String, String> JsonStrToMap(String json) {
        Map<String, String> map = new HashMap<>();
        try {
            map = MAPPER.readValue(json, Map.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return map;
    }

    /**
     * 将 Java 对象转为 JSON 字符串
     */
    public static String toJSONString(Object obj) {
        String jsonStr;
        try {
            jsonStr = MAPPER.writeValueAsString(obj);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return jsonStr;
    }

    /*
     * 001.json转换成对象
     * @param:传入对象，json字符串
     * @return:Object
     */
    public static <T> T jsonToObj(String jsonStr, Class<T> valueType) {
        try {
            return MAPPER.readValue(jsonStr, valueType);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * json字符串转成list
     *
     * @param jsonString
     * @param cls
     * @return
     */
    public static <T> List<T> jsonToList(String jsonString, Class<T> cls){
        try {
            return MAPPER.readValue(jsonString, getCollectionType(List.class, cls));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取泛型的Collection Type
     *
     * @param collectionClass 泛型的Collection
     * @param elementClasses  实体bean
     * @return JavaType Java类型
     */
    private static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return MAPPER.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }

}
