package com.example.removetolocal.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * JacksonUtil.
 *
 * @author Matrix <xhyrzldf@gmail.com>
 * @since 2020/8/15 at 7:30 下午
 */
public final class JacksonUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    }

    /**
     * 使用泛型方法，把json字符串转换为相应的JavaBean对象。
     * (1)转换为普通JavaBean：readValue(json,Student.class)
     * (2)转换为List,如List<Student>,将第二个参数传递为Student
     * [].class.然后使用Arrays.asList();方法把得到的数组转换为特定类型的List
     */
    public static <T> T readValue(String jsonStr, Class<T> valueType) {
        if (objectMapper == null) {
            objectMapper = new ObjectMapper();
        }
        try {
            return objectMapper.readValue(jsonStr, valueType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 转换为指定类型的集合
     *
     * @param jsonStr   待转换的json字符串
     * @param valueType 指定类型的Class对象
     * @return 指定类型的集合
     */
    public static <T> List<T> readValueToList(String jsonStr, Class<T> valueType) {
        T[] arrays = readValue(jsonStr, new TypeReference<T[]>() {
        });
        List<T> list = Collections.emptyList();
        if (arrays != null) {
            list = Arrays.asList(arrays);
        }
        return list;
    }

    /**
     * json数组转List
     *
     * @param jsonStr      待转换的json字符串
     * @param valueTypeRef 指定类型的Class对象
     * @return 指定类型的集合
     */
    public static <T> T readValue(String jsonStr, TypeReference<T> valueTypeRef) {
        if (objectMapper == null) {
            objectMapper = new ObjectMapper();
        }
        try {
            return objectMapper.readValue(jsonStr, valueTypeRef);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 把JavaBean转换为json字符串
     */
    public static String toJSon(Object object) {
        if (objectMapper == null) {
            objectMapper = new ObjectMapper();
        }

        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
