package com.secspace.lib.common.utils;

import android.text.TextUtils;
import android.util.ArrayMap;

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

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

/**
 * Created by bxy on 2018/6/15.
 */

public class JsonUtil {
    /**
     * 将对象序列化
     *
     * @param obj
     * @return
     */
    public static String toJson(Object obj) {
        if (obj == null) {
            throw new IllegalArgumentException("obj is null");
        }
        Gson gson = new Gson();
        return gson.toJson(obj);
    }

    public static List<String> json2StringList(String json) {
        if (TextUtils.isEmpty(json)) {
            return new ArrayList<>();
        }
        Gson gson = new Gson();
        return gson.fromJson(json, new TypeToken<List<String>>() {
        }.getType());
    }

    public static ArrayMap json2ArrayMap(String json) {
        if (TextUtils.isEmpty(json)) {
            return new ArrayMap<>();
        }
        Gson gson = new Gson();
        return gson.fromJson(json, new TypeToken<ArrayMap>() {
        }.getType());
    }

//    public static <T>T json2Class(String json) {
//        if (TextUtils.isEmpty(json)) {
//            return null;
//        }
//        Gson gson = new Gson();
//        Type type = ((ParameterizedType) T.class.getGenericSuperclass()).getActualTypeArguments()[0];
//        return gson.fromJson(json, new TypeToken<T>() {
//        }.getType());
//    }

    public static <T> T fromJson(String result, Class<T> classOfT) {
        if (result == null) {
            return null;
        }
        Gson gson = new Gson();
        return gson.fromJson(result, classOfT);
    }
}
