基于spring的redisTemplate的缓存工具类

来源:互联网 发布:金兰营销软件 编辑:程序博客网 时间:2024/06/04 20:00

1、spring相关配置如下:

Xml代码  收藏代码
  1.    
  2.     <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">  
  3.     <property name="maxIdle" value="${redis.pool.maxIdle}" /> <!-- 最大能够保持idel状态的对象数  -->  
  4.     <property name="maxTotal" value="${redis.pool.maxTotal}" /> <!-- 最大分配的对象数 -->  
  5.     <property name="testOnBorrow" value="${redis.pool.testOnBorrow}" /> <!-- 当调用borrow Object方法时,是否进行有效性检查 -->  
  6. </bean>  
  7.    
  8.     <!-- sprin_data_redis 单机配置 -->  
  9.     <bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >  
  10.         <property name="hostName" value="${redis.host}" />  
  11.         <property name="port" value="${redis.port}" />  
  12.         <property name="timeout" value="${redis.timeout}" />  
  13.         <property name="password" value="${redis.password}" />  
  14.         <property name="poolConfig" ref="jedisPoolConfig" />  
  15.     </bean>  
  16.     <!-- key序列化 -->  
  17. <bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" />  
  18.    
  19. <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"   
  20.     p:connectionFactory-ref="jedisConnFactory" />       
  21. <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"  
  22.     p:connectionFactory-ref="jedisConnFactory"   
  23.     p:keySerializer-ref="stringRedisSerializer"   
  24.     p:hashKeySerializer-ref="stringRedisSerializer" />  
  25. <!-- spring自己的缓存管理器 -->    
  26.    <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">    
  27.        <property name="caches">    
  28.            <set>    
  29.             <bean class="com.rd.ifaes.common.jedis.RdRedisCache" p:redis-template-ref="redisTemplate" p:name="sysCache"/>   
  30.            </set>    
  31.        </property>    
  32.    </bean>    
  33.   
  34. <!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效 -->  
  35. <cache:annotation-driven cache-manager="cacheManager" proxy-target-class="true" />  

 

2、缓存工具类CacheUtils

Java代码  收藏代码
  1. package com.lh.core.core.util;  
  2.   
  3. import java.util.Map;  
  4. import java.util.Set;  
  5. import java.util.concurrent.TimeUnit;  
  6.   
  7. import org.springframework.data.redis.core.BoundHashOperations;  
  8. import org.springframework.data.redis.core.RedisTemplate;  
  9. import org.springframework.data.redis.core.StringRedisTemplate;  
  10. import org.springframework.util.CollectionUtils;  
  11.   
  12. import com.alibaba.fastjson.JSON;  
  13. import com.alibaba.fastjson.JSONObject;  
  14. import com.rd.ifaes.common.dict.ExpireTime;  
  15. import com.lh.common.util.JsonMapper;  
  16. import com.rd.ifaes.common.util.SpringContextHolder;  
  17. import com.rd.ifaes.common.util.StringUtils;  
  18.   
  19. /** 
  20.  * 通用缓存工具类 
  21.  * @author lh 
  22.  * @version 3.0 
  23.  * @since 2016-6-22 
  24.  * 
  25.  */  
  26. public class CacheUtils {  
  27.       
  28.     private static StringRedisTemplate stringRedisTemplate = SpringContextHolder.getBean("stringRedisTemplate");  
  29.     private static RedisTemplate<String, Object> redisTemplate = SpringContextHolder.getBean("redisTemplate");  
  30.           
  31.     /** 
  32.      * 删除缓存<br> 
  33.      * 根据key精确匹配删除 
  34.      * @param key 
  35.      */  
  36.     @SuppressWarnings("unchecked")  
  37.     public static void del(String... key){  
  38.         if(key!=null && key.length > 0){  
  39.             if(key.length == 1){  
  40.                 redisTemplate.delete(key[0]);  
  41.             }else{  
  42.                 redisTemplate.delete(CollectionUtils.arrayToList(key));               
  43.             }  
  44.         }  
  45.     }  
  46.       
  47.     /** 
  48.      * 批量删除<br> 
  49.      * (该操作会执行模糊查询,请尽量不要使用,以免影响性能或误删) 
  50.      * @param pattern 
  51.      */   
  52.     public static void batchDel(String... pattern){  
  53.         for (String kp : pattern) {  
  54.             redisTemplate.delete(redisTemplate.keys(kp + "*"));  
  55.         }  
  56.     }  
  57.       
  58.     /** 
  59.      * 取得缓存(int型) 
  60.      * @param key 
  61.      * @return 
  62.      */  
  63.     public static Integer getInt(String key){  
  64.         String value = stringRedisTemplate.boundValueOps(key).get();  
  65.         if(StringUtils.isNotBlank(value)){  
  66.             return Integer.valueOf(value);  
  67.         }  
  68.         return null;  
  69.     }  
  70.       
  71.     /** 
  72.      * 取得缓存(字符串类型) 
  73.      * @param key 
  74.      * @return 
  75.      */  
  76.     public static String getStr(String key){  
  77.         return stringRedisTemplate.boundValueOps(key).get();  
  78.     }  
  79.       
  80.     /** 
  81.      * 取得缓存(字符串类型) 
  82.      * @param key 
  83.      * @return 
  84.      */  
  85.     public static String getStr(String key, boolean retain){  
  86.         String value = stringRedisTemplate.boundValueOps(key).get();  
  87.         if(!retain){  
  88.             redisTemplate.delete(key);  
  89.         }  
  90.         return value;  
  91.     }  
  92.       
  93.     /** 
  94.      * 获取缓存<br> 
  95.      * 注:基本数据类型(Character除外),请直接使用get(String key, Class<T> clazz)取值 
  96.      * @param key 
  97.      * @return 
  98.      */  
  99.     public static Object getObj(String key){  
  100.         return redisTemplate.boundValueOps(key).get();  
  101.     }  
  102.       
  103.     /** 
  104.      * 获取缓存<br> 
  105.      * 注:java 8种基本类型的数据请直接使用get(String key, Class<T> clazz)取值 
  106.      * @param key        
  107.      * @param retain    是否保留 
  108.      * @return 
  109.      */  
  110.     public static Object getObj(String key, boolean retain){  
  111.         Object obj = redisTemplate.boundValueOps(key).get();  
  112.         if(!retain){  
  113.             redisTemplate.delete(key);  
  114.         }  
  115.         return obj;  
  116.     }  
  117.       
  118.     /** 
  119.      * 获取缓存<br> 
  120.      * 注:该方法暂不支持Character数据类型 
  121.      * @param key   key 
  122.      * @param clazz 类型 
  123.      * @return 
  124.      */  
  125.     @SuppressWarnings("unchecked")  
  126.     public static <T> T get(String key, Class<T> clazz) {  
  127.         return (T)redisTemplate.boundValueOps(key).get();  
  128.     }  
  129.       
  130.     /** 
  131.      * 获取缓存json对象<br> 
  132.      * @param key   key 
  133.      * @param clazz 类型 
  134.      * @return 
  135.      */  
  136.     public static <T> T getJson(String key, Class<T> clazz) {  
  137.         return JsonMapper.fromJsonString(stringRedisTemplate.boundValueOps(key).get(), clazz);  
  138.     }  
  139.       
  140.     /** 
  141.      * 将value对象写入缓存 
  142.      * @param key 
  143.      * @param value 
  144.      * @param time 失效时间(秒) 
  145.      */  
  146.     public static void set(String key,Object value,ExpireTime time){  
  147.         if(value.getClass().equals(String.class)){  
  148.             stringRedisTemplate.opsForValue().set(key, value.toString());                 
  149.         }else if(value.getClass().equals(Integer.class)){  
  150.             stringRedisTemplate.opsForValue().set(key, value.toString());  
  151.         }else if(value.getClass().equals(Double.class)){  
  152.             stringRedisTemplate.opsForValue().set(key, value.toString());  
  153.         }else if(value.getClass().equals(Float.class)){  
  154.             stringRedisTemplate.opsForValue().set(key, value.toString());  
  155.         }else if(value.getClass().equals(Short.class)){  
  156.             stringRedisTemplate.opsForValue().set(key, value.toString());  
  157.         }else if(value.getClass().equals(Long.class)){  
  158.             stringRedisTemplate.opsForValue().set(key, value.toString());  
  159.         }else if(value.getClass().equals(Boolean.class)){  
  160.             stringRedisTemplate.opsForValue().set(key, value.toString());  
  161.         }else{  
  162.             redisTemplate.opsForValue().set(key, value);              
  163.         }  
  164.         if(time.getTime() > 0){  
  165.             redisTemplate.expire(key, time.getTime(), TimeUnit.SECONDS);  
  166.         }  
  167.     }  
  168.       
  169.     /** 
  170.      * 将value对象以JSON格式写入缓存 
  171.      * @param key 
  172.      * @param value 
  173.      * @param time 失效时间(秒) 
  174.      */  
  175.     public static void setJson(String key,Object value,ExpireTime time){  
  176.         stringRedisTemplate.opsForValue().set(key, JsonMapper.toJsonString(value));  
  177.         if(time.getTime() > 0){  
  178.             stringRedisTemplate.expire(key, time.getTime(), TimeUnit.SECONDS);  
  179.         }  
  180.     }  
  181.       
  182.     /** 
  183.      * 更新key对象field的值 
  184.      * @param key   缓存key 
  185.      * @param field 缓存对象field 
  186.      * @param value 缓存对象field值 
  187.      */  
  188.     public static void setJsonField(String key, String field, String value){  
  189.         JSONObject obj = JSON.parseObject(stringRedisTemplate.boundValueOps(key).get());  
  190.         obj.put(field, value);  
  191.         stringRedisTemplate.opsForValue().set(key, obj.toJSONString());  
  192.     }  
  193.       
  194.       
  195.     /** 
  196.      * 递减操作 
  197.      * @param key 
  198.      * @param by 
  199.      * @return 
  200.      */  
  201.     public static double decr(String key, double by){  
  202.         return redisTemplate.opsForValue().increment(key, -by);  
  203.     }  
  204.       
  205.     /** 
  206.      * 递增操作 
  207.      * @param key 
  208.      * @param by 
  209.      * @return 
  210.      */  
  211.     public static double incr(String key, double by){  
  212.         return redisTemplate.opsForValue().increment(key, by);  
  213.     }  
  214.       
  215.     /** 
  216.      * 获取double类型值 
  217.      * @param key 
  218.      * @return 
  219.      */  
  220.     public static double getDouble(String key) {  
  221.         String value = stringRedisTemplate.boundValueOps(key).get();  
  222.         if(StringUtils.isNotBlank(value)){  
  223.             return Double.valueOf(value);  
  224.         }  
  225.         return 0d;  
  226.     }  
  227.       
  228.     /** 
  229.      * 设置double类型值 
  230.      * @param key 
  231.      * @param value 
  232.      * @param time 失效时间(秒) 
  233.      */  
  234.     public static void setDouble(String key, double value, ExpireTime time) {  
  235.         stringRedisTemplate.opsForValue().set(key, String.valueOf(value));  
  236.         if(time.getTime() > 0){  
  237.             stringRedisTemplate.expire(key, time.getTime(), TimeUnit.SECONDS);  
  238.         }  
  239.     }  
  240.       
  241.     /** 
  242.      * 设置double类型值 
  243.      * @param key 
  244.      * @param value 
  245.      * @param time 失效时间(秒) 
  246.      */  
  247.     public static void setInt(String key, int value, ExpireTime time) {  
  248.         stringRedisTemplate.opsForValue().set(key, String.valueOf(value));  
  249.         if(time.getTime() > 0){  
  250.             stringRedisTemplate.expire(key, time.getTime(), TimeUnit.SECONDS);  
  251.         }  
  252.     }  
  253.       
  254.     /** 
  255.      * 将map写入缓存 
  256.      * @param key 
  257.      * @param map 
  258.      * @param time 失效时间(秒) 
  259.      */  
  260.     public static <T> void setMap(String key, Map<String, T> map, ExpireTime time){  
  261.         redisTemplate.opsForHash().putAll(key, map);  
  262.     }  
  263.       
  264.     /** 
  265.      * 将map写入缓存 
  266.      * @param key 
  267.      * @param map 
  268.      * @param time 失效时间(秒) 
  269.      */  
  270.     @SuppressWarnings("unchecked")  
  271.     public static <T> void setMap(String key, T obj, ExpireTime time){  
  272.         Map<String, String> map = (Map<String, String>)JsonMapper.parseObject(obj, Map.class);  
  273.         redisTemplate.opsForHash().putAll(key, map);  
  274.     }  
  275.       
  276.       
  277.       
  278.     /** 
  279.      * 向key对应的map中添加缓存对象 
  280.      * @param key 
  281.      * @param map 
  282.      */  
  283.     public static <T> void addMap(String key, Map<String, T> map){  
  284.         redisTemplate.opsForHash().putAll(key, map);  
  285.     }  
  286.       
  287.     /** 
  288.      * 向key对应的map中添加缓存对象 
  289.      * @param key   cache对象key 
  290.      * @param field map对应的key 
  291.      * @param value     值 
  292.      */  
  293.     public static void addMap(String key, String field, String value){  
  294.         redisTemplate.opsForHash().put(key, field, value);  
  295.     }  
  296.       
  297.     /** 
  298.      * 向key对应的map中添加缓存对象 
  299.      * @param key   cache对象key 
  300.      * @param field map对应的key 
  301.      * @param obj   对象 
  302.      */  
  303.     public static <T> void addMap(String key, String field, T obj){  
  304.         redisTemplate.opsForHash().put(key, field, obj);  
  305.     }  
  306.       
  307.     /** 
  308.      * 获取map缓存 
  309.      * @param key 
  310.      * @param clazz 
  311.      * @return 
  312.      */  
  313.     public static <T> Map<String, T> mget(String key, Class<T> clazz){  
  314.         BoundHashOperations<String, String, T> boundHashOperations = redisTemplate.boundHashOps(key);   
  315.         return boundHashOperations.entries();  
  316.     }  
  317.       
  318.     /** 
  319.      * 获取map缓存 
  320.      * @param key 
  321.      * @param clazz 
  322.      * @return 
  323.      */  
  324.     public static <T> T getMap(String key, Class<T> clazz){  
  325.         BoundHashOperations<String, String, String> boundHashOperations = redisTemplate.boundHashOps(key);   
  326.         Map<String, String> map = boundHashOperations.entries();  
  327.         return JsonMapper.parseObject(map, clazz);  
  328.     }  
  329.       
  330.     /** 
  331.      * 获取map缓存中的某个对象 
  332.      * @param key 
  333.      * @param field 
  334.      * @param clazz 
  335.      * @return 
  336.      */  
  337.     @SuppressWarnings("unchecked")  
  338.     public static <T> T getMapField(String key, String field, Class<T> clazz){  
  339.         return (T)redisTemplate.boundHashOps(key).get(field);  
  340.     }  
  341.       
  342.     /** 
  343.      * 删除map中的某个对象 
  344.      * @author lh 
  345.      * @date 2016年8月10日 
  346.      * @param key   map对应的key 
  347.      * @param field map中该对象的key 
  348.      */  
  349.     public void delMapField(String key, String... field){  
  350.         BoundHashOperations<String, String, ?> boundHashOperations = redisTemplate.boundHashOps(key);   
  351.         boundHashOperations.delete(field);  
  352.     }  
  353.       
  354.     /** 
  355.      * 指定缓存的失效时间 
  356.      *  
  357.      * @author FangJun 
  358.      * @date 2016年8月14日 
  359.      * @param key 缓存KEY 
  360.      * @param time 失效时间(秒) 
  361.      */  
  362.     public static void expire(String key, ExpireTime time) {  
  363.         if(time.getTime() > 0){  
  364.             redisTemplate.expire(key, time.getTime(), TimeUnit.SECONDS);  
  365.         }  
  366.     }  
  367.       
  368.     /** 
  369.      * 添加set 
  370.      * @param key 
  371.      * @param value 
  372.      */  
  373.     public static void sadd(String key, String... value) {  
  374.         redisTemplate.boundSetOps(key).add(value);  
  375.     }  
  376.   
  377.     /** 
  378.      * 删除set集合中的对象 
  379.      * @param key 
  380.      * @param value 
  381.      */  
  382.     public static void srem(String key, String... value) {  
  383.         redisTemplate.boundSetOps(key).remove(value);  
  384.     }  
  385.       
  386.     /** 
  387.      * set重命名 
  388.      * @param oldkey 
  389.      * @param newkey 
  390.      */  
  391.     public static void srename(String oldkey, String newkey){  
  392.         redisTemplate.boundSetOps(oldkey).rename(newkey);  
  393.     }  
  394.       
  395.     /** 
  396.      * 短信缓存 
  397.      * @author fxl 
  398.      * @date 2016年9月11日 
  399.      * @param key 
  400.      * @param value 
  401.      * @param time 
  402.      */  
  403.     public static void setIntForPhone(String key,Object value,int time){  
  404.         stringRedisTemplate.opsForValue().set(key, JsonMapper.toJsonString(value));  
  405.         if(time > 0){  
  406.             stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);  
  407.         }  
  408.     }  
  409.       
  410.     /** 
  411.      * 模糊查询keys 
  412.      * @param pattern 
  413.      * @return 
  414.      */  
  415.     public static Set<String> keys(String pattern){  
  416.         return redisTemplate.keys(pattern);   
  417.     }  
  418.       
  419. }  

 3、JsonMaper

Java代码  收藏代码
  1. package com.lh.common.util;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.TimeZone;  
  5.   
  6. import org.apache.commons.lang3.StringEscapeUtils;  
  7. import org.apache.commons.lang3.StringUtils;  
  8. import org.slf4j.Logger;  
  9. import org.slf4j.LoggerFactory;  
  10.   
  11. import com.alibaba.fastjson.JSON;  
  12. import com.fasterxml.jackson.annotation.JsonInclude.Include;  
  13. import com.fasterxml.jackson.core.JsonGenerator;  
  14. import com.fasterxml.jackson.core.JsonParser.Feature;  
  15. import com.fasterxml.jackson.core.JsonProcessingException;  
  16. import com.fasterxml.jackson.databind.DeserializationFeature;  
  17. import com.fasterxml.jackson.databind.JavaType;  
  18. import com.fasterxml.jackson.databind.JsonSerializer;  
  19. import com.fasterxml.jackson.databind.ObjectMapper;  
  20. import com.fasterxml.jackson.databind.SerializationFeature;  
  21. import com.fasterxml.jackson.databind.SerializerProvider;  
  22. import com.fasterxml.jackson.databind.module.SimpleModule;  
  23. import com.fasterxml.jackson.databind.util.JSONPObject;  
  24. import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;  
  25.   
  26.   
  27. /** 
  28.  * 简单封装Jackson,实现JSON String<->Java Object的Mapper. 
  29.  * 
  30.  */  
  31. public class JsonMapper extends ObjectMapper {  
  32.    
  33.         private static final long serialVersionUID = 1L;  
  34.   
  35.         private final static Logger LOGGER = LoggerFactory.getLogger(JsonMapper.class);  
  36.   
  37.         private static JsonMapper mapper;  
  38.   
  39.         public JsonMapper() {  
  40.             this(Include.NON_EMPTY);  
  41.         }  
  42.   
  43.         public JsonMapper(Include include) {  
  44.             // 设置输出时包含属性的风格  
  45.             if (include != null) {  
  46.                 this.setSerializationInclusion(include);  
  47.             }  
  48.             // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性  
  49.             this.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);  
  50.             // 空值处理为空串  
  51.             this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>(){  
  52.                 @Override  
  53.                 public void serialize(Object value, JsonGenerator jgen,  
  54.                         SerializerProvider provider) throws IOException,  
  55.                         JsonProcessingException {  
  56.                     jgen.writeString("");  
  57.                 }  
  58.             });  
  59.             // 进行HTML解码。  
  60.             this.registerModule(new SimpleModule().addSerializer(String.classnew JsonSerializer<String>(){  
  61.                 @Override  
  62.                 public void serialize(String value, JsonGenerator jgen,  
  63.                         SerializerProvider provider) throws IOException,  
  64.                         JsonProcessingException {  
  65.                     jgen.writeString(StringEscapeUtils.unescapeHtml4(value));  
  66.                 }  
  67.             }));  
  68.             // 设置时区  
  69.             this.setTimeZone(TimeZone.getDefault());//getTimeZone("GMT+8:00")  
  70.         }  
  71.   
  72.         /** 
  73.          * 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper,建议在外部接口中使用. 
  74.          */  
  75.         public static JsonMapper getInstance() {  
  76.             if (mapper == null){  
  77.                 mapper = new JsonMapper().enableSimple();  
  78.             }  
  79.             return mapper;  
  80.         }  
  81.   
  82.         /** 
  83.          * 创建只输出初始值被改变的属性到Json字符串的Mapper, 最节约的存储方式,建议在内部接口中使用。 
  84.          */  
  85.         public static JsonMapper nonDefaultMapper() {  
  86.             if (mapper == null){  
  87.                 mapper = new JsonMapper(Include.NON_DEFAULT);  
  88.             }  
  89.             return mapper;  
  90.         }  
  91.           
  92.         /** 
  93.          * Object可以是POJO,也可以是Collection或数组。 
  94.          * 如果对象为Null, 返回"null". 
  95.          * 如果集合为空集合, 返回"[]". 
  96.          */  
  97.         public String toJson(Object object) {  
  98.             try {  
  99.                 return this.writeValueAsString(object);  
  100.             } catch (IOException e) {  
  101.                 if(LOGGER.isWarnEnabled()){  
  102.                     LOGGER.warn("write to json string error:" + object, e);  
  103.                 }  
  104.                 return null;  
  105.             }  
  106.         }  
  107.   
  108.         /** 
  109.          * 反序列化POJO或简单Collection如List<String>. 
  110.          *  
  111.          * 如果JSON字符串为Null或"null"字符串, 返回Null. 
  112.          * 如果JSON字符串为"[]", 返回空集合. 
  113.          *  
  114.          * 如需反序列化复杂Collection如List<MyBean>, 请使用fromJson(String,JavaType) 
  115.          * @see #fromJson(String, JavaType) 
  116.          */  
  117.         public <T> T fromJson(String jsonString, Class<T> clazz) {  
  118.             if (StringUtils.isEmpty(jsonString)) {  
  119.                 return null;  
  120.             }  
  121.             try {  
  122.                 return this.readValue(jsonString, clazz);  
  123.             } catch (IOException e) {  
  124.                 if(LOGGER.isWarnEnabled()){  
  125.                     LOGGER.warn("parse json string error:" + jsonString, e);  
  126.                 }  
  127.                 return null;  
  128.             }  
  129.         }  
  130.   
  131.         /** 
  132.          * 反序列化复杂Collection如List<Bean>, 先使用函數createCollectionType构造类型,然后调用本函数. 
  133.          * @see #createCollectionType(Class, Class...) 
  134.          */  
  135.         @SuppressWarnings("unchecked")  
  136.         public <T> T fromJson(String jsonString, JavaType javaType) {  
  137.             if (StringUtils.isEmpty(jsonString)) {  
  138.                 return null;  
  139.             }  
  140.             try {  
  141.                 return (T) this.readValue(jsonString, javaType);  
  142.             } catch (IOException e) {  
  143.                 if(LOGGER.isWarnEnabled()){  
  144.                     LOGGER.warn("parse json string error:" + jsonString, e);  
  145.                 }  
  146.                 return null;  
  147.             }  
  148.         }  
  149.   
  150.         /** 
  151.          * 構造泛型的Collection Type如: 
  152.          * ArrayList<MyBean>, 则调用constructCollectionType(ArrayList.class,MyBean.class) 
  153.          * HashMap<String,MyBean>, 则调用(HashMap.class,String.class, MyBean.class) 
  154.          */  
  155.         public JavaType createCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {  
  156.             return this.getTypeFactory().constructParametricType(collectionClass, elementClasses);  
  157.         }  
  158.   
  159.         /** 
  160.          * 當JSON裡只含有Bean的部分屬性時,更新一個已存在Bean,只覆蓋該部分的屬性. 
  161.          */  
  162.         @SuppressWarnings("unchecked")  
  163.         public <T> T update(String jsonString, T object) {  
  164.             try {  
  165.                 return (T) this.readerForUpdating(object).readValue(jsonString);  
  166.             } catch (JsonProcessingException e) {  
  167.                 if(LOGGER.isWarnEnabled()){  
  168.                     LOGGER.warn("update json string:" + jsonString + " to object:" + object + " error.", e);  
  169.                 }  
  170.             } catch (IOException e) {  
  171.                 if(LOGGER.isWarnEnabled()){  
  172.                     LOGGER.warn("update json string:" + jsonString + " to object:" + object + " error.", e);  
  173.                 }  
  174.             }  
  175.             return null;  
  176.         }  
  177.   
  178.         /** 
  179.          * 輸出JSONP格式數據. 
  180.          */  
  181.         public String toJsonP(String functionName, Object object) {  
  182.             return toJson(new JSONPObject(functionName, object));  
  183.         }  
  184.   
  185.         /** 
  186.          * 設定是否使用Enum的toString函數來讀寫Enum, 
  187.          * 為False時時使用Enum的name()函數來讀寫Enum, 默認為False. 
  188.          * 注意本函數一定要在Mapper創建後, 所有的讀寫動作之前調用. 
  189.          */  
  190.         public JsonMapper enableEnumUseToString() {  
  191.             this.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);  
  192.             this.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);  
  193.             return this;  
  194.         }  
  195.   
  196.         /** 
  197.          * 支持使用Jaxb的Annotation,使得POJO上的annotation不用与Jackson耦合。 
  198.          * 默认会先查找jaxb的annotation,如果找不到再找jackson的。 
  199.          */  
  200.         public JsonMapper enableJaxbAnnotation() {  
  201.             JaxbAnnotationModule module = new JaxbAnnotationModule();  
  202.             this.registerModule(module);  
  203.             return this;  
  204.         }  
  205.   
  206.         /** 
  207.          * 允许单引号 
  208.          * 允许不带引号的字段名称 
  209.          */  
  210.         public JsonMapper enableSimple() {  
  211.             this.configure(Feature.ALLOW_SINGLE_QUOTES, true);  
  212.             this.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);  
  213.             return this;  
  214.         }  
  215.           
  216.         /** 
  217.          * 取出Mapper做进一步的设置或使用其他序列化API. 
  218.          */  
  219.         public ObjectMapper getMapper() {  
  220.             return this;  
  221.         }  
  222.   
  223.         /** 
  224.          * 对象转换为JSON字符串 
  225.          * @param object 
  226.          * @return 
  227.          */  
  228.         public static String toJsonString(Object object){  
  229.             return JsonMapper.getInstance().toJson(object);  
  230.         }  
  231.           
  232.         /** 
  233.          * JSON字符串转换为对象 
  234.          * @param jsonString 
  235.          * @param clazz 
  236.          * @return 
  237.          */  
  238.         public static <T> T fromJsonString(String jsonString, Class<T> clazz){  
  239.             return JsonMapper.getInstance().fromJson(jsonString, clazz);  
  240.         }  
  241.           
  242.           
  243.         /** 
  244.          * 将obj对象转换成 class类型的对象 
  245.          * @param obj 
  246.          * @param clazz 
  247.          * @return 
  248.          */  
  249.         public static <T> T parseObject(Object obj, Class<T> clazz){  
  250.             return JSON.parseObject(JSON.toJSONString(obj), clazz);  
  251.         }  
  252.           
  253. }  
  254. 地址:http://hbxflihua.iteye.com/blog/2328156