package com.xhly.corelib.utils;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.xhly.corelib.network.bean.ResponseData;

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

public class GsonUtils {
    //将Json数据解析成相应的映射对象
    public static <T> T parseJsonWithGson(String jsonData, Class<T> type) {
        if (TextUtils.isEmpty(jsonData) || jsonData.length() < 6) {
            return null;
        }
        Gson gson = new Gson();
        T result = null;
        try {
            result = gson.fromJson(jsonData, type);
        } catch (Exception e) {
            LogUtils.d(GsonUtils.class.getName(), "解析异常："+e.getMessage() + "\n 内容是：" + jsonData);
            e.printStackTrace();
            return null;
        }
        return result;
    }

    /**
     * 将Json数组解析成相应的映射对象列表
     */
    public static <T> ArrayList<T> parseJsonArrayWithGson(String jsonData,
                                                          Class<T> type) {
        if (TextUtils.isEmpty(jsonData) || jsonData.length() < 6) {
            return null;
        }
        ArrayList<T> mList = new ArrayList<>();
        JsonArray array = null;
        try {
            array = new JsonParser().parse(jsonData).getAsJsonArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        for (final JsonElement elem : array) {
            mList.add(new Gson().fromJson(elem, type));
        }
        return mList;
    }

    public static String parseClassToJson(Object object) {
        if (null == object) {
            return "";
        }
        Gson gson = new Gson();
        return gson.toJson(object);
    }
    //将Json数据解析成ResponseData
    public static ResponseData fromJson(String json, Class clazz) {
        Gson gson = new Gson();
        Type objectType = type(ResponseData.class, clazz);
        return gson.fromJson(json, objectType);
    }


    static ParameterizedType type(final Class raw, final Type... args) {
        return new ParameterizedType() {
            @Override
            public Type getRawType() {
                return raw;
            }

            @Override
            public Type[] getActualTypeArguments() {
                return args;
            }

            @Override
            public Type getOwnerType() {
                return null;
            }
        };
    }
}
