package me.zhengjie.util;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import lombok.extern.java.Log;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

/**
 * json 转换工具类
 * @author Administrator
 *
 */
@Log
public class JSONUtil {
	/**
	 * log for this class
	 */

	private static Gson gson = new GsonBuilder().serializeNulls().create();// 保存NULL
	public static String toJsonString(Object o){
		return gson.toJson(o);
	}

	public static String toJsonString(Object o,String  dateFormat){
		Gson gson2 = new GsonBuilder().serializeNulls().setDateFormat(dateFormat).create();
		log.info(gson2.toJson(o));
		return gson2.toJson(o);
	}
	public static String ToJsongString2(Object o){
		return JSON.toJSONString(o);
	}

	public static Object fromJson(String str,Class beanClass){
		Gson gson = new Gson();
		try {
			if(str!=null){
				Object obj = gson.fromJson(str, beanClass);
				return obj;
			}else{
				log.info("JSONUtil.fromJson ERR===>>>>>>"+str);
				return null;
			}
		}catch (Exception e){
			log.info("JSONUtil.fromJson ERR===>>>>>>"+str);
			e.printStackTrace();
		}
		return null;
	}

	/**
     * 将Json对象转换成Map
     *
     * @param jsonObject
     *            json对象
     * @return Map对象
     * @throws JSONException
     */

	public static Map toMap(String jsonString) {
        Gson gson = new Gson();
        Type type = new TypeToken<Map<String ,? >>() {}.getType();
        Map   map = (Map)gson.fromJson(jsonString, type);
        return map;
    }
	/**
	 * json 转换成List
	 * @param jsonString
	 * @return
	 * @throws JSONException
	 */
	public static List toList(String jsonString){
        Gson gson = new Gson();
        List list = gson.fromJson(jsonString, new TypeToken<List>(){}.getType());
        return list;
    }

	/**
	 * json转换实体bean
	 * @param json
	 * @param c
	 * @return
	 * @throws Exception
	 */
	public static <T> T converyToJavaBean(String json, Class<T> c)throws Exception {
		Gson gson = new Gson();
		return gson.fromJson(json, c);
	}

}
