• JsonUtils工具整理


    import java.lang.reflect.Type;
    
    import org.apache.commons.pool2.impl.GenericObjectPool;
    import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
    
    import com.google.gson.Gson;
    public class JsonPoolUtils {
    
        private static ThreadLocal<JsonPoolUtils> instance = new ThreadLocal<JsonPoolUtils>();
    
        protected static GenericObjectPool<Gson> pool;
    
        static {
            if (instance.get() == null || pool == null) {
                GenericObjectPoolConfig conf = new GenericObjectPoolConfig();
                conf.setMaxTotal(32);
                conf.setMaxIdle(4);
                pool = new GenericObjectPool<Gson>(new PooledGsonFactory(), conf);
            }
        }
    
        public final static <T> T fromJson(String json, Type typeOfT) {
            if (json == null) {
                return null;
            }
            Gson gson = null;
            try {
                gson = pool.borrowObject();
            } catch (Exception e) {
                e.printStackTrace();
            }
            T t = gson.fromJson(json, typeOfT);
            pool.returnObject(gson);
            return t;
        }
    
        public final static String toJson(Object src) {
            if (src == null) {
                return null;
            }
            Gson gson = null;
            try {
                gson = pool.borrowObject();
            } catch (Exception e) {
                e.printStackTrace();
            }
            String string = gson.toJson(src);
            pool.returnObject(gson);
            return string;
        }
    }
    import java.sql.Timestamp;
    
    import org.apache.commons.pool2.BasePooledObjectFactory;
    import org.apache.commons.pool2.PooledObject;
    import org.apache.commons.pool2.impl.DefaultPooledObject;
    
    import com.google.gson.Gson;
    import com.google.gson.GsonBuilder;
    
    public class PooledGsonFactory extends BasePooledObjectFactory<Gson> {
    
        @Override
        public Gson create() throws Exception {
            return new GsonBuilder().registerTypeAdapter(Timestamp.class, new TimestampTypeAdapter()).create();
        }
    
        @Override
        public PooledObject<Gson> wrap(Gson obj) {
            return new DefaultPooledObject<Gson>(obj);
        }
    
    }
  • 相关阅读:
    C++ 项目和资源导引
    C++ 类再探
    C++ 语句函数再探
    leetcode-174. Dungeon Game 地下城游戏
    34. Find First and Last Position of Element in Sorted Array + 二分
    leetcode-27. Remove Element删除元素
    git 使用入门
    MySQL数据库的启动与停止
    C++类型转换
    C++ 获取对象类型
  • 原文地址:https://www.cnblogs.com/light-zhang/p/8745126.html
Copyright © 2020-2023  润新知