package com.gingersoft.gsa.cloud.base.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import java.util.List;

/**
 * Created by Wyh on 2020/1/16.
 */
public class JsonUtils {

    private static JsonUtils gsonUtils;

    public static JsonUtils getInstance() {
        if (gsonUtils == null) {
            synchronized (JsonUtils.class) {
                if (gsonUtils == null) {
                    gsonUtils = new JsonUtils();
                }
            }
        }
        return gsonUtils;
    }


    /**
     * json字符串转换bean对象，异常捕捉
     */
    public static <T> T parseObject(String json, Class<T> classOfT) {
        try {
            if (null == json) {
                return null;
            }
            return JSON.parseObject(json, classOfT);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * object转换List对象，异常捕捉
     */
    public static <T> List<T> parseArray(Object object, Class<T> classOfT) {
        try {
            if (null == object) {
                return null;
            }
            return parseArray(JSONObject.toJSONString(object), classOfT);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * json字符串转换List对象，异常捕捉
     */
    public static <T> List<T> parseArray(String json, Class<T> classOfT) {
        try {
            if (null == json) {
                return null;
            }
            return JSON.parseArray(json, classOfT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String toJson(Object o) {
        try {
            return JSON.toJSONString(o);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
