使用Gson的转换java类型

Java代码 复制代码
  1. import java.util.Iterator;   
  2. import java.util.Collection;   
  3. import java.util.Enumeration;   
  4. import java.lang.reflect.Type;   
  5. import org.apache.commons.logging.Log;   
  6. import org.apache.commons.logging.LogFactory;   
  7. import com.google.gson.Gson;   
  8. import com.google.gson.GsonBuilder;   
  9. import com.google.gson.reflect.TypeToken;   
  10. /**  
  11.  * 包含操作 {@code JSON} 数据的常用方法的工具类。  
  12.  * <p>  
  13.  * 该工具类使用的 {@code JSON} 转换引擎是 <a href="http://code.google.com/p/google-gson/" mce_href="http://code.google.com/p/google-gson/"  
  14.  * target="_blank">{@code Google Gson}</a>。下面是工具类的使用案例:  
  15.  * </p>  
  16.  *   
  17.  * <pre>  
  18.  * public class User {  
  19.  *     {@literal @SerializedName("pwd")}  
  20.  *     private String password;  
  21.  *     {@literal @Expose}  
  22.  *     {@literal @SerializedName("uname")}  
  23.  *     private String username;  
  24.  *     {@literal @Expose}  
  25.  *     {@literal @Since(1.1)}  
  26.  *     private String gender;  
  27.  *     {@literal @Expose}  
  28.  *     {@literal @Since(1.0)}  
  29.  *     private String sex;  
  30.  *       
  31.  *     public User() {}  
  32.  *     public User(String username, String password, String gender) {  
  33.  *         // user constructor code... ... ...  
  34.  *     }  
  35.  *       
  36.  *     public String getUsername()  
  37.  *     ... ... ...  
  38.  * }  
  39.  * List<User> userList = new LinkedList<User>();  
  40.  * User jack = new User("Jack", "123456", "Male");  
  41.  * User marry = new User("Marry", "888888", "Female");  
  42.  * userList.add(jack);  
  43.  * userList.add(marry);  
  44.  * Type targetType = new TypeToken<List<User>>(){}.getType();  
  45.  * String sUserList1 = JSONUtils.toJson(userList, targetType);  
  46.  * sUserList1 ----> [{"uname":"jack","gender":"Male","sex":"Male"},{"uname":"marry","gender":"Female","sex":"Female"}]  
  47.  * String sUserList2 = JSONUtils.toJson(userList, targetType, false);  
  48.  * sUserList2 ----> [{"uname":"jack","pwd":"123456","gender":"Male","sex":"Male"},{"uname":"marry","pwd":"888888","gender":"Female","sex":"Female"}]  
  49.  * String sUserList3 = JSONUtils.toJson(userList, targetType, 1.0d, true);  
  50.  * sUserList3 ----> [{"uname":"jack","sex":"Male"},{"uname":"marry","sex":"Female"}]  
  51.  * </pre>  
  52.  *   
  53.  * @author Fuchun  
  54.  * @version 1.0, 2009-6-27  
  55.  */  
  56. public class JSONUtils extends Utils {   
  57.     @SuppressWarnings("unused")   
  58.     private static final Log log = LogFactory.getLog(JSONUtils.class);   
  59.     /** 空的 {@code JSON} 数据 - <code>"{}"</code>。 */  
  60.     public static final String EMPTY_JSON = "{}";   
  61.     /** 空的 {@code JSON} 数组(集合)数据 - {@code "[]"}。 */  
  62.     public static final String EMPTY_JSON_ARRAY = "[]";   
  63.     /** 默认的 {@code JSON} 日期/时间字段的格式化模式。 */  
  64.     public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss SSS";   
  65.     /** {@code Google Gson} 的 {@literal @Since} 注解常用的版本号常量 - {@code 1.0}。 */  
  66.     public static final Double SINCE_VERSION_10 = 1.0d;   
  67.     /** {@code Google Gson} 的 {@literal @Since} 注解常用的版本号常量 - {@code 1.1}。 */  
  68.     public static final Double SINCE_VERSION_11 = 1.1d;   
  69.     /** {@code Google Gson} 的 {@literal @Since} 注解常用的版本号常量 - {@code 1.2}。 */  
  70.     public static final Double SINCE_VERSION_12 = 1.2d;   
  71.     /**  
  72.      * 将给定的目标对象根据指定的条件参数转换成 {@code JSON} 格式的字符串。  
  73.      * <p />  
  74.      * <strong>该方法转换发生错误时,不会抛出任何异常。若发生错误时,曾通对象返回 <code>"{}"</code>;  
  75.      * 集合或数组对象返回 <code>"[]"</code></strong>  
  76.      *   
  77.      * @param target 目标对象。  
  78.      * @param targetType 目标对象的类型。  
  79.      * @param isSerializeNulls 是否序列化 {@code null} 值字段。  
  80.      * @param version 字段的版本号注解。  
  81.      * @param datePattern 日期字段的格式化模式。  
  82.      * @param excludesFieldsWithoutExpose 是否排除未标注 {@literal @Expose} 注解的字段。  
  83.      * @return 目标对象的 {@code JSON} 格式的字符串。  
  84.      */  
  85.     public static String toJson(Object target, Type targetType, boolean isSerializeNulls,   
  86.             Double version, String datePattern, boolean excludesFieldsWithoutExpose) {   
  87.         if (target == null)   
  88.             return EMPTY_JSON;   
  89.         GsonBuilder builder = new GsonBuilder();   
  90.         if (isSerializeNulls)   
  91.             builder.serializeNulls();   
  92.         if (version != null)   
  93.             builder.setVersion(version.doubleValue());   
  94.         if (isEmpty(datePattern))   
  95.             datePattern = DEFAULT_DATE_PATTERN;   
  96.         builder.setDateFormat(datePattern);   
  97.         if (excludesFieldsWithoutExpose)   
  98.             builder.excludeFieldsWithoutExposeAnnotation();   
  99.         String result = EMPTY;   
  100.         Gson gson = builder.create();   
  101.         try {   
  102.             if (targetType != null) {   
  103.                 result = gson.toJson(target, targetType);   
  104.             } else {   
  105.                 result = gson.toJson(target);   
  106.             }   
  107.         } catch (Exception ex) {   
  108.             log.warn("目标对象 " + target.getClass().getName() + " 转换 JSON 字符串时,发生异常!", ex);   
  109.             if (target instanceof Collection || target instanceof Iterator   
  110.                     || target instanceof Enumeration || target.getClass().isArray()) {   
  111.                 result = EMPTY_JSON_ARRAY;   
  112.             } else  
  113.                 result = EMPTY_JSON;   
  114.         }   
  115.         return result;   
  116.     }   
  117.     /**  
  118.      * 将给定的目标对象转换成 {@code JSON} 格式的字符串。<strong>此方法只用来转换普通的 {@code JavaBean} 对象。</strong>  
  119.      * <ul>  
  120.      * <li>该方法只会转换标有 {@literal @Expose} 注解的字段;</li>  
  121.      * <li>该方法不会转换 {@code null} 值字段;</li>  
  122.      * <li>该方法会转换所有未标注或已标注 {@literal @Since} 的字段;</li>  
  123.      * <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss SSS};</li>  
  124.      * </ul>  
  125.      *   
  126.      * @param target 要转换成 {@code JSON} 的目标对象。  
  127.      * @return 目标对象的 {@code JSON} 格式的字符串。  
  128.      */  
  129.     public static String toJson(Object target) {   
  130.         return toJson(target, nullfalsenullnulltrue);   
  131.     }   
  132.     /**  
  133.      * 将给定的目标对象转换成 {@code JSON} 格式的字符串。<strong>此方法只用来转换普通的 {@code JavaBean} 对象。</strong>  
  134.      * <ul>  
  135.      * <li>该方法只会转换标有 {@literal @Expose} 注解的字段;</li>  
  136.      * <li>该方法不会转换 {@code null} 值字段;</li>  
  137.      * <li>该方法会转换所有未标注或已标注 {@literal @Since} 的字段;</li>  
  138.      * </ul>  
  139.      *   
  140.      * @param target 要转换成 {@code JSON} 的目标对象。  
  141.      * @param datePattern 日期字段的格式化模式。  
  142.      * @return 目标对象的 {@code JSON} 格式的字符串。  
  143.      */  
  144.     public static String toJson(Object target, String datePattern) {   
  145.         return toJson(target, nullfalsenull, datePattern, true);   
  146.     }   
  147.     /**  
  148.      * 将给定的目标对象转换成 {@code JSON} 格式的字符串。<strong>此方法只用来转换普通的 {@code JavaBean} 对象。</strong>  
  149.      * <ul>  
  150.      * <li>该方法只会转换标有 {@literal @Expose} 注解的字段;</li>  
  151.      * <li>该方法不会转换 {@code null} 值字段;</li>  
  152.      * <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss SSS};</li>  
  153.      * </ul>  
  154.      *   
  155.      * @param target 要转换成 {@code JSON} 的目标对象。  
  156.      * @param version 字段的版本号注解({@literal @Since})。  
  157.      * @return 目标对象的 {@code JSON} 格式的字符串。  
  158.      */  
  159.     public static String toJson(Object target, Double version) {   
  160.         return toJson(target, nullfalse, version, nulltrue);   
  161.     }   
  162.     /**  
  163.      * 将给定的目标对象转换成 {@code JSON} 格式的字符串。<strong>此方法只用来转换普通的 {@code JavaBean} 对象。</strong>  
  164.      * <ul>  
  165.      * <li>该方法不会转换 {@code null} 值字段;</li>  
  166.      * <li>该方法会转换所有未标注或已标注 {@literal @Since} 的字段;</li>  
  167.      * <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss SSS};</li>  
  168.      * </ul>  
  169.      *   
  170.      * @param target 要转换成 {@code JSON} 的目标对象。  
  171.      * @param excludesFieldsWithoutExpose 是否排除未标注 {@literal @Expose} 注解的字段。  
  172.      * @return 目标对象的 {@code JSON} 格式的字符串。  
  173.      */  
  174.     public static String toJson(Object target, boolean excludesFieldsWithoutExpose) {   
  175.         return toJson(target, nullfalsenullnull, excludesFieldsWithoutExpose);   
  176.     }   
  177.     /**  
  178.      * 将给定的目标对象转换成 {@code JSON} 格式的字符串。<strong>此方法只用来转换普通的 {@code JavaBean} 对象。</strong>  
  179.      * <ul>  
  180.      * <li>该方法不会转换 {@code null} 值字段;</li>  
  181.      * <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss SSS};</li>  
  182.      * </ul>  
  183.      *   
  184.      * @param target 要转换成 {@code JSON} 的目标对象。  
  185.      * @param version 字段的版本号注解({@literal @Since})。  
  186.      * @param excludesFieldsWithoutExpose 是否排除未标注 {@literal @Expose} 注解的字段。  
  187.      * @return 目标对象的 {@code JSON} 格式的字符串。  
  188.      */  
  189.     public static String toJson(Object target, Double version, boolean excludesFieldsWithoutExpose) {   
  190.         return toJson(target, nullfalse, version, null, excludesFieldsWithoutExpose);   
  191.     }   
  192.     /**  
  193.      * 将给定的目标对象转换成 {@code JSON} 格式的字符串。<strong>此方法通常用来转换使用泛型的对象。</strong>  
  194.      * <ul>  
  195.      * <li>该方法只会转换标有 {@literal @Expose} 注解的字段;</li>  
  196.      * <li>该方法不会转换 {@code null} 值字段;</li>  
  197.      * <li>该方法会转换所有未标注或已标注 {@literal @Since} 的字段;</li>  
  198.      * <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss SSSS};</li>  
  199.      * </ul>  
  200.      *   
  201.      * @param target 要转换成 {@code JSON} 的目标对象。  
  202.      * @param targetType 目标对象的类型。  
  203.      * @return 目标对象的 {@code JSON} 格式的字符串。  
  204.      */  
  205.     public static String toJson(Object target, Type targetType) {   
  206.         return toJson(target, targetType, falsenullnulltrue);   
  207.     }   
  208.     /**  
  209.      * 将给定的目标对象转换成 {@code JSON} 格式的字符串。<strong>此方法通常用来转换使用泛型的对象。</strong>  
  210.      * <ul>  
  211.      * <li>该方法只会转换标有 {@literal @Expose} 注解的字段;</li>  
  212.      * <li>该方法不会转换 {@code null} 值字段;</li>  
  213.      * <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss SSSS};</li>  
  214.      * </ul>  
  215.      *   
  216.      * @param target 要转换成 {@code JSON} 的目标对象。  
  217.      * @param targetType 目标对象的类型。  
  218.      * @param version 字段的版本号注解({@literal @Since})。  
  219.      * @return 目标对象的 {@code JSON} 格式的字符串。  
  220.      */  
  221.     public static String toJson(Object target, Type targetType, Double version) {   
  222.         return toJson(target, targetType, false, version, nulltrue);   
  223.     }   
  224.     /**  
  225.      * 将给定的目标对象转换成 {@code JSON} 格式的字符串。<strong>此方法通常用来转换使用泛型的对象。</strong>  
  226.      * <ul>  
  227.      * <li>该方法不会转换 {@code null} 值字段;</li>  
  228.      * <li>该方法会转换所有未标注或已标注 {@literal @Since} 的字段;</li>  
  229.      * <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss SSS};</li>  
  230.      * </ul>  
  231.      *   
  232.      * @param target 要转换成 {@code JSON} 的目标对象。  
  233.      * @param targetType 目标对象的类型。  
  234.      * @param excludesFieldsWithoutExpose 是否排除未标注 {@literal @Expose} 注解的字段。  
  235.      * @return 目标对象的 {@code JSON} 格式的字符串。  
  236.      */  
  237.     public static String toJson(Object target, Type targetType, boolean excludesFieldsWithoutExpose) {   
  238.         return toJson(target, targetType, falsenullnull, excludesFieldsWithoutExpose);   
  239.     }   
  240.     /**  
  241.      * 将给定的目标对象转换成 {@code JSON} 格式的字符串。<strong>此方法通常用来转换使用泛型的对象。</strong>  
  242.      * <ul>  
  243.      * <li>该方法不会转换 {@code null} 值字段;</li>  
  244.      * <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss SSS};</li>  
  245.      * </ul>  
  246.      *   
  247.      * @param target 要转换成 {@code JSON} 的目标对象。  
  248.      * @param targetType 目标对象的类型。  
  249.      * @param version 字段的版本号注解({@literal @Since})。  
  250.      * @param excludesFieldsWithoutExpose 是否排除未标注 {@literal @Expose} 注解的字段。  
  251.      * @return 目标对象的 {@code JSON} 格式的字符串。  
  252.      */  
  253.     public static String toJson(Object target, Type targetType, Double version,   
  254.             boolean excludesFieldsWithoutExpose) {   
  255.         return toJson(target, targetType, false, version, null, excludesFieldsWithoutExpose);   
  256.     }   
  257.     /**  
  258.      * 将给定的 {@code JSON} 字符串转换成指定的类型对象。  
  259.      *   
  260.      * @param <T> 要转换的目标类型。  
  261.      * @param json 给定的 {@code JSON} 字符串。  
  262.      * @param token {@code com.google.gson.reflect.TypeToken} 的类型指示类对象。  
  263.      * @param datePattern 日期格式模式。  
  264.      * @return 给定的 {@code JSON} 字符串表示的指定的类型对象。  
  265.      */  
  266.     public static <T> T fromJson(String json, TypeToken<T> token, String datePattern) {   
  267.         if (isEmpty(json)) {   
  268.             return null;   
  269.         }   
  270.         GsonBuilder builder = new GsonBuilder();   
  271.         if (isEmpty(datePattern)) {   
  272.             datePattern = DEFAULT_DATE_PATTERN;   
  273.         }   
  274.         Gson gson = builder.create();   
  275.         try {   
  276.             return gson.fromJson(json, token.getType());   
  277.         } catch (Exception ex) {   
  278.             log.error(json + " 无法转换为 " + token.getRawType().getName() + " 对象!", ex);   
  279.             return null;   
  280.         }   
  281.     }   
  282.     /**  
  283.      * 将给定的 {@code JSON} 字符串转换成指定的类型对象。  
  284.      *   
  285.      * @param <T> 要转换的目标类型。  
  286.      * @param json 给定的 {@code JSON} 字符串。  
  287.      * @param token {@code com.google.gson.reflect.TypeToken} 的类型指示类对象。  
  288.      * @return 给定的 {@code JSON} 字符串表示的指定的类型对象。  
  289.      */  
  290.     public static <T> T fromJson(String json, TypeToken<T> token) {   
  291.         return fromJson(json, token, null);   
  292.     }   
  293.     /**  
  294.      * 将给定的 {@code JSON} 字符串转换成指定的类型对象。<strong>此方法通常用来转换普通的 {@code JavaBean}  
  295.      * 对象。</strong>  
  296.      *   
  297.      * @param <T> 要转换的目标类型。  
  298.      * @param json 给定的 {@code JSON} 字符串。  
  299.      * @param clazz 要转换的目标类。  
  300.      * @param datePattern 日期格式模式。  
  301.      * @return 给定的 {@code JSON} 字符串表示的指定的类型对象。  
  302.      */  
  303.     public static <T> T fromJson(String json, Class<T> clazz, String datePattern) {   
  304.         if (isEmpty(json)) {   
  305.             return null;   
  306.         }   
  307.         GsonBuilder builder = new GsonBuilder();   
  308.         if (isEmpty(datePattern)) {   
  309.             datePattern = DEFAULT_DATE_PATTERN;   
  310.         }   
  311.         Gson gson = builder.create();   
  312.         try {   
  313.             return gson.fromJson(json, clazz);   
  314.         } catch (Exception ex) {   
  315.             log.error(json + " 无法转换为 " + clazz.getName() + " 对象!", ex);   
  316.             return null;   
  317.         }   
  318.     }   
  319.     /**  
  320.      * 将给定的 {@code JSON} 字符串转换成指定的类型对象。<strong>此方法通常用来转换普通的 {@code JavaBean}  
  321.      * 对象。</strong>  
  322.      *   
  323.      * @param <T> 要转换的目标类型。  
  324.      * @param json 给定的 {@code JSON} 字符串。  
  325.      * @param clazz 要转换的目标类。  
  326.      * @return 给定的 {@code JSON} 字符串表示的指定的类型对象。  
  327.      */  
  328.     public static <T> T fromJson(String json, Class<T> clazz) {   
  329.         return fromJson(json, clazz, null);   
  330.     }   
  331. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值