日期:2014-05-16  浏览次数:20349 次

实用的json工具类gson
涉及到的jar包主要是gson-2.0.jar(必须),log4j.jar(可选)



使用方法


1,对象转字符串:String str = JsonUtils.toJson(A, false)//第一个参数具体对象,第二个正常情况下一定要设为false

转回对象A:
 A  a = JsonUtils.fromJson(str , A.calss)
,第一个是通过json转的string,第二个参数目标对象

注意:如果是把List对象转String,而List里面的对象中又包含了其他对象,在取出的时候不能用foreach循环取出,

请采用如下方式

List roList = JsonUtils.fromJson(str,List.class); //str是List转为的string对象

for (int i = 0; i < roList.size(); i++) {

ResultObject ro = JsonUtils.fromJson(JsonUtils.toJson(roList.get(i), false),

ResultObject.class);

}


更多关于原生json内容请参考http://learning.iteye.com/blog/1289255
    import java.lang.reflect.Type;  
    import java.util.Collection;  
    import java.util.Enumeration;  
    import java.util.Iterator;  
      
    import org.apache.commons.logging.Log;  
    import org.apache.commons.logging.LogFactory;  
      
    import com.google.gson.Gson;  
    import com.google.gson.GsonBuilder;  
    import com.google.gson.reflect.TypeToken;  
      
    public class JsonUtils {  
        private static final Log log = LogFactory.getLog(JsonUtils.class);  
        public static final String EMPTY = "";  
        /** 空的 {@code JSON} 数据 - <code>"{}"</code>。 */  
        public static final String EMPTY_JSON = "{}";  
        /** 空的 {@code JSON} 数组(集合)数据 - {@code "[]"}。 */  
        public static final String EMPTY_JSON_ARRAY = "[]";  
        /** 默认的 {@code JSON} 日期/时间字段的格式化模式。 */  
        public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss SSS";  
        /** {@code Google Gson} 的 {@literal @Since} 注解常用的版本号常量 - {@code 1.0}。 */  
        public static final Double SINCE_VERSION_10 = 1.0d;  
        /** {@code Google Gson} 的 {@literal @Since} 注解常用的版本号常量 - {@code 1.1}。 */  
        public static final Double SINCE_VERSION_11 = 1.1d;  
        /** {@code Google Gson} 的 {@literal @Since} 注解常用的版本号常量 - {@code 1.2}。 */  
        public static final Double SINCE_VERSION_12 = 1.2d;  
      
        /** 
         * 将给定的目标对象根据指定的条件参数转换成 {@code JSON} 格式的字符串。 
         * <p /> 
         * <strong>该方法转换发生错误时,不会抛出任何异常。若发生错误时,曾通对象返回 <code>"{}"</code>; 集合或数组对象返回 
         * <code>"[]"</code></strong> 
         *  
         * @param target 
         *            目标对象。 
         * @param targetType 
         *            目标对象的类型。 
         * @param isSerializeNulls 
         *            是否序列化 {@code null} 值字段。 
         * @param version 
         *            字段的版本号注解。 
         * @param datePattern 
         *            日期字段的格式化模式。 
         * @param excludesFieldsWithoutExpose 
         *            是否排除未标注 {@literal @Expose} 注解的字段。 
         * @return 目标对象的 {@code JSON} 格式的字符串。 
         */  
        public static String toJson(Object target, Type targetType,  
                boolean isSerializeNulls, Double version, String datePattern,  
                boolean excludesFieldsWithoutExpose) {  
            if (target == null)  
                return EMPTY_JSON;  
            GsonBuilder builder = new GsonBuilder();  
            if (isSerializeNulls)  
                builder.serializeNulls();  
            if (version != null)  
                builder.setVersion(version.doubleValue());  
            if (isEmpty(datePattern))  
                datePattern = DEFAULT_DATE_PATTERN;  
            builder.setDateFormat(datePattern);  
            if (excludesFieldsWithoutExpose)  
                builder.excludeFieldsWithoutExposeAnnotation();  
            String result = EMPTY;  
            Gson gson = builder.create();  
            try {  
                if (targetType != null) {  
                    result = gson.toJson(target, targetType);  
                } else {  
                    result = gson.toJson(target);  
                }  
            } catch (Exception e