GsonUtil

package com.example.et.Ustlis;


import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class GsonUtil {
    private static Gson gson = null;

    static {
        if (gson == null) {
            gson = new Gson();
        }
    }

    private GsonUtil() {
    }

    /**
     * 转成json
     *
     * @param object
     * @return
     */
    public static String BeanToJson(Object object) {
        String gsonString = null;
        if (gson != null) {
            gsonString = gson.toJson(object);
        }
        return gsonString;
    }

    /**
     * 转成bean
     *
     * @param gsonString
     * @param cls
     * @return
     */
    public static  T GsonToBean(String gsonString, Class cls) {
        T t = null;
        if (gson != null) {
            t = gson.fromJson(gsonString, cls);
        }
        return t;
    }

    /**
     * 转成list
     * 泛型在编译期类型被擦除导致报错
     *
     * @param gsonString
     * @param cls
     * @return
     */
    public static  List GsonToList(String gsonString, Class cls) {
        List list = null;
        if (gson != null) {
            list = gson.fromJson(gsonString, new TypeToken>() {
            }.getType());
        }
        return list;
    }

    /**
     * 转成list
     * 解决泛型问题
     *
     * @param json
     * @param cls
     * @param 
     * @return
     */
    public static   List jsonToList(String json, Class cls) {
        Gson gson = new Gson();
        List list = new ArrayList();
        JsonArray array = new JsonParser().parse(json).getAsJsonArray();
        for (final JsonElement elem : array) {
            list.add(gson.fromJson(elem, cls));
        }
        return list;
    }


    /**
     * 转成list中有map的
     *
     * @param gsonString
     * @return
     */
    public static  List> GsonToListMaps(String gsonString) {
        List> list = null;
        if (gson != null) {
            list = gson.fromJson(gsonString,
                    new TypeToken>>() {
                    }.getType());
        }
        return list;
    }

    /**
     * 转成map的
     *
     * @param gsonString
     * @return
     */
    public static  Map GsonToMaps(String gsonString) {
        Map map = null;
        if (gson != null) {
            map = gson.fromJson(gsonString, new TypeToken>() {
            }.getType());
        }
        return map;
    }
}

 

你可能感兴趣的:(GsonUtil)