package com.app.baselibrary.commonUtil;

import android.content.Context;

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

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created by henry  16/1/30.
 */
public class JsonUtils {
    public static Gson mGson = new Gson();
    static final String TAG = JsonUtils.class.getSimpleName();
    /**
     * JsonString-->object
     *
     * @param jsonString string
     * @return object
     */
    public static <T> T stringToObject(String jsonString, Class<T> t) {
        return str2obj(jsonString, t);
    }

    /**
     * 使用 fastJson 解析
     *
     * @param t   t
     * @param <T> T
     * @return T
     */
    public static <T> List<T> parseList(String str, Class<T> t) {
        try {
            Type type = new TypeToken<T>() {
            }.getType();

            return mGson.fromJson(str, type);
        } catch (Exception e) {
            return null;
        }


    }
    public static <T> T str2obj(String str, Class<T> cls) {
        try {
            return mGson.fromJson(str, cls);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * string转换为map
     */

    public static LinkedHashMap<String, String> jsonToMap(String str) {
        LinkedHashMap<String, String>
                map = new Gson().fromJson(str, new TypeToken<HashMap<String, Object>>() {
        }.getType());
        return map;
    }
    /**
     * 读取assets下的txt文件，返回utf-8 String
     * @param context
     * @param fileName 不包括后缀
     * @return
     */
    public static <T> T readAssetsTxt(Context context, String fileName, Class<T> cls){
        try {
            //Return an AssetManager instance for your application's package
            InputStream is = context.getAssets().open(fileName+".txt");
            int size = is.available();
            // Read the entire asset into a local byte buffer.
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            // Convert the buffer into a string.
            String text = new String(buffer, "utf-8");
            // Finally stick the string into the oo view.
            return str2obj(text,cls);
        } catch (IOException e) {
            // Should never happen!
//            throw new RuntimeException(e);
            e.printStackTrace();
        }
        return null;
    }
}
