zoukankan      html  css  js  c++  java
  • 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);
        }
    
    }
  • 相关阅读:
    ARPG手游实战练习(八)
    ARPG手游实战练习(七)
    ARPG手游实战练习(六)
    ARPG手游实战练习(五)
    ARPG手游实战练习(四)
    ARPG手游实战练习(三)
    C# Array类的Sort()方法
    C#继承讲解以及对象的创建
    单例模式
    愤怒的小鸟(练习版)
  • 原文地址:https://www.cnblogs.com/light-zhang/p/8745126.html
Copyright © 2011-2022 走看看