実用的なjsonツールクラスgson

18244 ワード

関連するjarパッケージは主にgson-2.0である.JAr(必須)、log 4 j.JAr(オプション)
使用方法
1,オブジェクト回転文字列:String str=JsonUtils.toJson(A,false)//1番目のパラメータの具体的な対象、2番目の正常な情況の下で必ずfalseに設定します
対象Aに戻る:
 A  a = JsonUtils.fromJson(str , A.calss)
、1つ目はjson回転string、2つ目のパラメータターゲットオブジェクト
注意:リストオブジェクトをStringに回し、リスト内のオブジェクトに他のオブジェクトが含まれている場合、取り出すときに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 ex) {  
                log.warn("     " + target.getClass().getName()  
                        + "    JSON     ,    !", ex);  
                if (target instanceof Collection || target instanceof Iterator  
                        || target instanceof Enumeration  
                        || target.getClass().isArray()) {  
                    result = EMPTY_JSON_ARRAY;  
                } else  
                    result = EMPTY_JSON;  
            }  
            return result;  
        }  
      
        /** 
         *             {@code JSON}       。<strong>            {@code JavaBean} 
         *   。</strong> 
         * <ul> 
         * <li>          {@literal @Expose}      ;</li> 
         * <li>        {@code null}    ;</li> 
         * <li>                {@literal @Since}    ;</li> 
         * <li>              /         - {@code yyyy-MM-dd HH:mm:ss SSS};</li> 
         * </ul> 
         *  
         * @param target 
         *                 {@code JSON}      。 
         * @return       {@code JSON}       。 
         */  
        public static String toJson(Object target) {  
            return toJson(target, null, false, null, null, true);  
        }  
      
        /** 
         *             {@code JSON}       。<strong>            {@code JavaBean} 
         *   。</strong> 
         * <ul> 
         * <li>          {@literal @Expose}      ;</li> 
         * <li>        {@code null}    ;</li> 
         * <li>                {@literal @Since}    ;</li> 
         * </ul> 
         *  
         * @param target 
         *                 {@code JSON}      。 
         * @param datePattern 
         *                      。 
         * @return       {@code JSON}       。 
         */  
        public static String toJson(Object target, String datePattern) {  
            return toJson(target, null, false, null, datePattern, true);  
        }  
      
        /** 
         *             {@code JSON}       。<strong>            {@code JavaBean} 
         *   。</strong> 
         * <ul> 
         * <li>          {@literal @Expose}      ;</li> 
         * <li>        {@code null}    ;</li> 
         * <li>              /         - {@code yyyy-MM-dd HH:mm:ss SSS};</li> 
         * </ul> 
         *  
         * @param target 
         *                 {@code JSON}      。 
         * @param version 
         *                    ({@literal @Since})。 
         * @return       {@code JSON}       。 
         */  
        public static String toJson(Object target, Double version) {  
            return toJson(target, null, false, version, null, true);  
        }  
      
        /** 
         *             {@code JSON}       。<strong>            {@code JavaBean} 
         *   。</strong> 
         * <ul> 
         * <li>        {@code null}    ;</li> 
         * <li>                {@literal @Since}    ;</li> 
         * <li>              /         - {@code yyyy-MM-dd HH:mm:ss SSS};</li> 
         * </ul> 
         *  
         * @param target 
         *                 {@code JSON}      。 
         * @param excludesFieldsWithoutExpose 
         *                    {@literal @Expose}      。 
         * @return       {@code JSON}       。 
         */  
        public static String toJson(Object target,  
                boolean excludesFieldsWithoutExpose) {  
            return toJson(target, null, false, null, null,  
                    excludesFieldsWithoutExpose);  
        }  
      
        /** 
         *             {@code JSON}       。<strong>            {@code JavaBean} 
         *   。</strong> 
         * <ul> 
         * <li>        {@code null}    ;</li> 
         * <li>              /         - {@code yyyy-MM-dd HH:mm:ss SSS};</li> 
         * </ul> 
         *  
         * @param target 
         *                 {@code JSON}      。 
         * @param version 
         *                    ({@literal @Since})。 
         * @param excludesFieldsWithoutExpose 
         *                    {@literal @Expose}      。 
         * @return       {@code JSON}       。 
         */  
        public static String toJson(Object target, Double version,  
                boolean excludesFieldsWithoutExpose) {  
            return toJson(target, null, false, version, null,  
                    excludesFieldsWithoutExpose);  
        }  
      
        /** 
         *             {@code JSON}       。<strong>                。</strong> 
         * <ul> 
         * <li>          {@literal @Expose}      ;</li> 
         * <li>        {@code null}    ;</li> 
         * <li>                {@literal @Since}    ;</li> 
         * <li>              /         - {@code yyyy-MM-dd HH:mm:ss SSSS};</li> 
         * </ul> 
         *  
         * @param target 
         *                 {@code JSON}      。 
         * @param targetType 
         *                   。 
         * @return       {@code JSON}       。 
         */  
        public static String toJson(Object target, Type targetType) {  
            return toJson(target, targetType, false, null, null, true);  
        }  
      
        /** 
         *             {@code JSON}       。<strong>                。</strong> 
         * <ul> 
         * <li>          {@literal @Expose}      ;</li> 
         * <li>        {@code null}    ;</li> 
         * <li>              /         - {@code yyyy-MM-dd HH:mm:ss SSSS};</li> 
         * </ul> 
         *  
         * @param target 
         *                 {@code JSON}      。 
         * @param targetType 
         *                   。 
         * @param version 
         *                    ({@literal @Since})。 
         * @return       {@code JSON}       。 
         */  
        public static String toJson(Object target, Type targetType, Double version) {  
            return toJson(target, targetType, false, version, null, true);  
        }  
      
        /** 
         *             {@code JSON}       。<strong>                。</strong> 
         * <ul> 
         * <li>        {@code null}    ;</li> 
         * <li>                {@literal @Since}    ;</li> 
         * <li>              /         - {@code yyyy-MM-dd HH:mm:ss SSS};</li> 
         * </ul> 
         *  
         * @param target 
         *                 {@code JSON}      。 
         * @param targetType 
         *                   。 
         * @param excludesFieldsWithoutExpose 
         *                    {@literal @Expose}      。 
         * @return       {@code JSON}       。 
         */  
        public static String toJson(Object target, Type targetType,  
                boolean excludesFieldsWithoutExpose) {  
            return toJson(target, targetType, false, null, null,  
                    excludesFieldsWithoutExpose);  
        }  
      
        /** 
         *             {@code JSON}       。<strong>                。</strong> 
         * <ul> 
         * <li>        {@code null}    ;</li> 
         * <li>              /         - {@code yyyy-MM-dd HH:mm:ss SSS};</li> 
         * </ul> 
         *  
         * @param target 
         *                 {@code JSON}      。 
         * @param targetType 
         *                   。 
         * @param version 
         *                    ({@literal @Since})。 
         * @param excludesFieldsWithoutExpose 
         *                    {@literal @Expose}      。 
         * @return       {@code JSON}       。 
         */  
        public static String toJson(Object target, Type targetType, Double version,  
                boolean excludesFieldsWithoutExpose) {  
            return toJson(target, targetType, false, version, null,  
                    excludesFieldsWithoutExpose);  
        }  
      
        /** 
         *      {@code JSON}              。 
         *  
         * @param <T> 
         *                    。 
         * @param json 
         *                {@code JSON}    。 
         * @param token 
         *            {@code com.google.gson.reflect.TypeToken}         。 
         * @param datePattern 
         *                  。 
         * @return     {@code JSON}              。 
         */  
        public static <T> T fromJson(String json, TypeToken<T> token,  
                String datePattern) {  
            if (isEmpty(json)) {  
                return null;  
            }  
            GsonBuilder builder = new GsonBuilder();  
            if (isEmpty(datePattern)) {  
                datePattern = DEFAULT_DATE_PATTERN;  
            }  
            Gson gson = builder.create();  
            try {  
                return gson.fromJson(json, token.getType());  
            } catch (Exception ex) {  
                log.error(json + "       " + token.getRawType().getName() + "   !",  
                        ex);  
                return null;  
            }  
        }  
      
        /** 
         *      {@code JSON}              。 
         *  
         * @param <T> 
         *                    。 
         * @param json 
         *                {@code JSON}    。 
         * @param token 
         *            {@code com.google.gson.reflect.TypeToken}         。 
         * @return     {@code JSON}              。 
         */  
        public static <T> T fromJson(String json, TypeToken<T> token) {  
            return fromJson(json, token, null);  
        }  
      
        /** 
         *      {@code JSON}              。<strong>             {@code JavaBean} 
         *   。</strong> 
         *  
         * @param <T> 
         *                    。 
         * @param json 
         *                {@code JSON}    。 
         * @param clazz 
         *                   。 
         * @param datePattern 
         *                  。 
         * @return     {@code JSON}              。 
         */  
        public static <T> T fromJson(String json, Class<T> clazz, String datePattern) {  
            if (isEmpty(json)) {  
                return null;  
            }  
            GsonBuilder builder = new GsonBuilder();  
            if (isEmpty(datePattern)) {  
                datePattern = DEFAULT_DATE_PATTERN;  
            }  
            Gson gson = builder.create();  
            try {  
                return gson.fromJson(json, clazz);  
            } catch (Exception ex) {  
                log.error(json + "       " + clazz.getName() + "   !", ex);  
                return null;  
            }  
        }  
      
        /** 
         *      {@code JSON}              。<strong>             {@code JavaBean} 
         *   。</strong> 
         *  
         * @param <T> 
         *                    。 
         * @param json 
         *                {@code JSON}    。 
         * @param clazz 
         *                   。 
         * @return     {@code JSON}              。 
         */  
        public static <T> T fromJson(String json, Class<T> clazz) {  
            return fromJson(json, clazz, null);  
        }  
      
        public static boolean isEmpty(String inStr) {  
            boolean reTag = false;  
            if (inStr == null || "".equals(inStr)) {  
                reTag = true;  
            }  
            return reTag;  
        }  
    }  


JArパッケージのダウンロードの詳細は、次のとおりです.
http://code.google.com/p/google-gson/
gsonユーザーマニュアルの詳細は以下を参照してください.
https://sites.google.com/site/gson/gson-user-guide