GsonUtil工具类

package com.llw.dan.driver.utils;

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

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

/**
 * Created by Administrator on 2017/6/17.
 */

public class GsonUtil {
        private static Gson gson = null;
        static {
            if (gson == null) {
                gson = new Gson();
            }
        }

        private GsonUtil() {
        }

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

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

        /**
         * 转成list
         *
         * @param gsonString
         * @param cls
         * @return
         */
        public static <T> List<T> GsonToList(String gsonString, Class<T> cls) {
            List<T> list = null;
            if (gson != null) {
                list = gson.fromJson(gsonString, new TypeTokenT>>() {
                }.getType());
            }
            return list;
        }

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

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

你可能感兴趣的:(GsonUtil工具类)