天天看點

實用的json工具類gson

涉及到的jar包主要是gson-2.0.jar(必須),log4j.jar(可選)

使用方法

1,對象轉字元串:String str = JsonUtils.toJson(A, false)//第一個參數具體對象,第二個正常情況下一定要設為false

轉回對象A: Java代碼  

實用的json工具類gson
  1. A  a = JsonUtils.fromJson(str , A.calss)  

,第一個是通過json轉的string,第二個參數目标對象

注意:如果是把List對象轉String,而List裡面的對象中又包含了其他對象,在取出的時候不能用foreach循環取出,

請采用如下方式

Java代碼  

實用的json工具類gson
  1. List roList = JsonUtils.fromJson(str,List.class); //str是List轉為的string對象  
  2. for (int i = 0; i < roList.size(); i++) {  
  3. ResultObject ro = JsonUtils.fromJson(JsonUtils.toJson(roList.get(i), false),  
  4. ResultObject.class);  
  5. }  

更多關于原生json内容請參考http://learning.iteye.com/blog/1289255

Java代碼  

實用的json工具類gson
  1. import java.lang.reflect.Type;    
  2. import java.util.Collection;    
  3. import java.util.Enumeration;    
  4. import java.util.Iterator;    
  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. public class JsonUtils {    
  11.     private static final Log log = LogFactory.getLog(JsonUtils.class);    
  12.     public static final String EMPTY = "";    
  13.     public static final String EMPTY_JSON = "{}";    
  14.     public static final String EMPTY_JSON_ARRAY = "[]";    
  15.     public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss SSS";    
  16.     public static final Double SINCE_VERSION_10 = 1.0d;    
  17.     public static final Double SINCE_VERSION_11 = 1.1d;    
  18.     public static final Double SINCE_VERSION_12 = 1.2d;    
  19.     public static String toJson(Object target, Type targetType,    
  20.             boolean isSerializeNulls, Double version, String datePattern,    
  21.             boolean excludesFieldsWithoutExpose) {    
  22.         if (target == null)    
  23.             return EMPTY_JSON;    
  24.         GsonBuilder builder = new GsonBuilder();    
  25.         if (isSerializeNulls)    
  26.             builder.serializeNulls();    
  27.         if (version != null)    
  28.             builder.setVersion(version.doubleValue());    
  29.         if (isEmpty(datePattern))    
  30.             datePattern = DEFAULT_DATE_PATTERN;    
  31.         builder.setDateFormat(datePattern);    
  32.         if (excludesFieldsWithoutExpose)    
  33.             builder.excludeFieldsWithoutExposeAnnotation();    
  34.         String result = EMPTY;    
  35.         Gson gson = builder.create();    
  36.         try {    
  37.             if (targetType != null) {    
  38.                 result = gson.toJson(target, targetType);    
  39.             } else {    
  40.                 result = gson.toJson(target);    
  41.             }    
  42.         } catch (Exception ex) {    
  43.             log.warn("目标對象 " + target.getClass().getName()    
  44.                     + " 轉換 JSON 字元串時,發生異常!", ex);    
  45.             if (target instanceof Collection || target instanceof Iterator    
  46.                     || target instanceof Enumeration    
  47.                     || target.getClass().isArray()) {    
  48.                 result = EMPTY_JSON_ARRAY;    
  49.             } else    
  50.                 result = EMPTY_JSON;    
  51.         }    
  52.         return result;    
  53.     }    
  54.     public static String toJson(Object target) {    
  55.         return toJson(target, null, false, null, null, true);    
  56.     }    
  57.     public static String toJson(Object target, String datePattern) {    
  58.         return toJson(target, null, false, null, datePattern, true);    
  59.     }    
  60.     public static String toJson(Object target, Double version) {    
  61.         return toJson(target, null, false, version, null, true);    
  62.     }    
  63.     public static String toJson(Object target,    
  64.             boolean excludesFieldsWithoutExpose) {    
  65.         return toJson(target, null, false, null, null,    
  66.                 excludesFieldsWithoutExpose);    
  67.     }    
  68.     public static String toJson(Object target, Double version,    
  69.             boolean excludesFieldsWithoutExpose) {    
  70.         return toJson(target, null, false, version, null,    
  71.                 excludesFieldsWithoutExpose);    
  72.     }    
  73.     public static String toJson(Object target, Type targetType) {    
  74.         return toJson(target, targetType, false, null, null, true);    
  75.     }    
  76.     public static String toJson(Object target, Type targetType, Double version) {    
  77.         return toJson(target, targetType, false, version, null, true);    
  78.     }    
  79.     public static String toJson(Object target, Type targetType,    
  80.             boolean excludesFieldsWithoutExpose) {    
  81.         return toJson(target, targetType, false, null, null,    
  82.                 excludesFieldsWithoutExpose);    
  83.     }    
  84.     public static String toJson(Object target, Type targetType, Double version,    
  85.             boolean excludesFieldsWithoutExpose) {    
  86.         return toJson(target, targetType, false, version, null,    
  87.                 excludesFieldsWithoutExpose);    
  88.     }    
  89.     public static <T> T fromJson(String json, TypeToken<T> token,    
  90.             String datePattern) {    
  91.         if (isEmpty(json)) {    
  92.             return null;    
  93.         }    
  94.         GsonBuilder builder = new GsonBuilder();    
  95.         if (isEmpty(datePattern)) {    
  96.             datePattern = DEFAULT_DATE_PATTERN;    
  97.         }    
  98.         Gson gson = builder.create();    
  99.         try {    
  100.             return gson.fromJson(json, token.getType());    
  101.         } catch (Exception ex) {    
  102.             log.error(json + " 無法轉換為 " + token.getRawType().getName() + " 對象!",    
  103.                     ex);    
  104.             return null;    
  105.         }    
  106.     }    
  107.     public static <T> T fromJson(String json, TypeToken<T> token) {    
  108.         return fromJson(json, token, null);    
  109.     }    
  110.     public static <T> T fromJson(String json, Class<T> clazz, String datePattern) {    
  111.         if (isEmpty(json)) {    
  112.             return null;    
  113.         }    
  114.         GsonBuilder builder = new GsonBuilder();    
  115.         if (isEmpty(datePattern)) {    
  116.             datePattern = DEFAULT_DATE_PATTERN;    
  117.         }    
  118.         Gson gson = builder.create();    
  119.         try {    
  120.             return gson.fromJson(json, clazz);    
  121.         } catch (Exception ex) {    
  122.             log.error(json + " 無法轉換為 " + clazz.getName() + " 對象!", ex);    
  123.             return null;    
  124.         }    
  125.     }    
  126.     public static <T> T fromJson(String json, Class<T> clazz) {    
  127.         return fromJson(json, clazz, null);    
  128.     }    
  129.     public static boolean isEmpty(String inStr) {    
  130.         boolean reTag = false;    
  131.         if (inStr == null || "".equals(inStr)) {    
  132.             reTag = true;    
  133.         }    
  134.         return reTag;    
  135.     }    
  136. }