package com.miraclegarden.smsmessage;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

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

/**
 * json解析工具类
 * @author
 */
public class GsonUtils {

	private static final String TAG = "GsonUtils";
	public static Gson gson = new Gson();

	/**
	 * 返回List对象
	 * @param str
	 * @param type new TypeToken<ArrayList<T>>(){}.getType()
	 * @param <T>
     * @return
     */
	public static <T> T getListFromJSON(String str, Type type) {
		if (!TextUtils.isEmpty(str)) {
			try {
				return gson.fromJson(str, type);
			} catch (Exception e) {
				Log.e(TAG, "getListFromJSON(Type) parse error", e);
				return null;
			}
		}
		return null;
	}

	/**
	 * 返回List对象
	 * @param str
	 * @param cls
	 * @param <T>
     * @return
     */
	public static <T> List<T> getListFromJSON(String str, Class<T> cls) {
		if (TextUtils.isEmpty(str)) {
			return new ArrayList<>();
		}
		try {
			Type type = new TypeToken<ArrayList<JsonObject>>()
			{}.getType();
			ArrayList<JsonObject> jsonObjects = gson.fromJson(str, type);
			if (jsonObjects == null) {
				return new ArrayList<>();
			}
			ArrayList<T> arrayList = new ArrayList<>();
			for (JsonObject jsonObject : jsonObjects) {
				arrayList.add(gson.fromJson(jsonObject, cls));
			}
			return arrayList;
		} catch (Exception e) {
			Log.e(TAG, "getListFromJSON(Class) parse error", e);
			return new ArrayList<>();
		}
	}

	/**
	 * 返回对象
	 * @param str
	 * @param cls
	 * @param <T>
     * @return
     */
	public static <T> T getObjFromJSON(String str, Class<T> cls) {
		try {
			if (!TextUtils.isEmpty(str)) {
				return gson.fromJson(str, cls);
			}
			return null;
		} catch (Exception e) {
			Log.e(TAG, "getObjFromJSON parse error", e);
			return null;
		}
	}

	/**
	 * 返回JsonString
	 * @return
	 */
	public static String beanToJSONString(Object bean) {
		if (bean == null) {
			return "";
		}
		try {
			return gson.toJson(bean);
		} catch (Exception e) {
			Log.e(TAG, "beanToJSONString error", e);
			return "";
		}
	}


	public static String JSONTokener(String in) {
		// consume an optional byte order mark (BOM) if it exists
		if (in != null && in.startsWith("\ufeff")) {
			in = in.substring(1);
		}
		return in;
	}

}
