Java tutorial
package com.vko.core.common.util.gson; /* * Copyright 2010 Fuchun. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.lang.reflect.Type; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; /** * ?? {@code JSON} ? * <p /> * {@code JSON} ? <a href="http://code.google.com/p/google-gson/" * mce_href="http://code.google.com/p/google-gson/" target="_blank"> {@code * Google Gson}</a> ? * * <pre> * public class User { * @SerializedName("pwd") * private String password; * @Expose * @SerializedName("uname") * private String username; * @Expose * @Since(1.1) * private String gender; * @Expose * @Since(1.0) * private String sex; * * public User() {} * public User(String username, String password, String gender) { * // user constructor code... ... ... * } * * public String getUsername() * ... ... ... * } * List<User> userList = new LinkedList<User>(); * User jack = new User("Jack", "123456", "Male"); * User marry = new User("Marry", "888888", "Female"); * userList.add(jack); * userList.add(marry); * Type targetType = new TypeToken<List<User>>(){}.getType(); * String sUserList1 = JSONUtils.toJson(userList, targetType); * sUserList1 ----> [{"uname":"jack","gender":"Male","sex":"Male"},{"uname":"marry","gender":"Female","sex":"Female"}] * String sUserList2 = JSONUtils.toJson(userList, targetType, false); * sUserList2 ----> [{"uname":"jack","pwd":"123456","gender":"Male","sex":"Male"},{"uname":"marry","pwd":"888888","gender":"Female","sex":"Female"}] * String sUserList3 = JSONUtils.toJson(userList, targetType, 1.0d, true); * sUserList3 ----> [{"uname":"jack","sex":"Male"},{"uname":"marry","sex":"Female"}] * </pre> * * @author Fuchun * @since ay-commons-lang 1.0 * @version 1.1.0 */ public class GsonUtil { private static final Logger LOGGER = LoggerFactory.getLogger(GsonUtil.class); /** {@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} <code>@Since</code> ?? - {@code 1.0} */ public static final double SINCE_VERSION_10 = 1.0d; /** {@code Google Gson} <code>@Since</code> ?? - {@code 1.1} */ public static final double SINCE_VERSION_11 = 1.1d; /** {@code Google Gson} <code>@Since</code> ?? - {@code 1.2} */ public static final double SINCE_VERSION_12 = 1.2d; /** {@code Google Gson} <code>@Until</code> ?? - {@code 1.0} */ public static final double UNTIL_VERSION_10 = SINCE_VERSION_10; /** {@code Google Gson} <code>@Until</code> ?? - {@code 1.1} */ public static final double UNTIL_VERSION_11 = SINCE_VERSION_11; /** {@code Google Gson} <code>@Until</code> ?? - {@code 1.2} */ public static final double UNTIL_VERSION_12 = SINCE_VERSION_12; /** * <p> * <code>JSONUtils</code> instances should NOT be constructed in standard * programming. Instead, the class should be used as * <code>JSONUtils.fromJson("foo");</code>. * </p> * <p> * This constructor is public to permit tools that require a JavaBean * instance to operate. * </p> */ public GsonUtil() { super(); } /** * ????? {@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} ? * @since 1.0 */ 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 (StringUtils.isBlank(datePattern)) datePattern = DEFAULT_DATE_PATTERN; builder.setDateFormat(datePattern); if (excludesFieldsWithoutExpose) builder.excludeFieldsWithoutExposeAnnotation(); return toJson(target, targetType, builder); } /** * ?? {@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} ? * @since 1.0 */ 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} ? * @since 1.0 */ 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} ? * @since 1.0 */ 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} ? * @since 1.0 */ 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} ? * @since 1.0 */ 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} ? * @since 1.0 */ 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} ? * @since 1.0 */ 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} ? * @since 1.0 */ 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} ? * @since 1.0 */ 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} * @since 1.0 */ public static <T> T fromJson(String json, TypeToken<T> token, String datePattern) { if (StringUtils.isBlank(json)) { return null; } GsonBuilder builder = new GsonBuilder(); if (StringUtils.isBlank(datePattern)) { datePattern = DEFAULT_DATE_PATTERN; } Gson gson = builder.create(); try { return (T) gson.fromJson(json, token.getType()); } catch (Exception ex) { LOGGER.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} * @since 1.0 */ 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} * @since 1.0 */ public static <T> T fromJson(String json, Class<T> clazz, String datePattern) { if (StringUtils.isBlank(json)) { return null; } GsonBuilder builder = new GsonBuilder(); if (StringUtils.isBlank(datePattern)) { datePattern = DEFAULT_DATE_PATTERN; } Gson gson = builder.create(); try { return gson.fromJson(json, clazz); } catch (Exception ex) { LOGGER.error(json + " ? " + clazz.getName() + " !", ex); return null; } } /** * {@code JSON} ??<strong>?? {@code JavaBean} * </strong> * * @param <T> * ?? * @param json * {@code JSON} * @param clazz * ?? * @return {@code JSON} * @since 1.0 */ public static <T> T fromJson(String json, Class<T> clazz) { return fromJson(json, clazz, null); } /** * ?{@code GsonBuilder} ???? {@code JSON} ? * <p /> * ????{@code JavaBean} <code>"{}"</code> * ? <code>"[]"</code> * * @param target * * @param targetType * * @param builder * ?{@code Gson} * @return {@code JSON} ? * @since 1.1 */ public static String toJson(Object target, Type targetType, GsonBuilder builder) { if (target == null) return EMPTY_JSON; Gson gson = null; if (builder == null) { gson = new Gson(); } else { gson = builder.create(); } String result = EMPTY_JSON; try { if (targetType == null) { result = gson.toJson(target); } else { result = gson.toJson(target, targetType); } } catch (Exception ex) { LOGGER.warn( " " + target.getClass().getName() + " ? JSON ??", ex); if (target instanceof Collection<?> || target instanceof Iterator<?> || target instanceof Enumeration<?> || target.getClass().isArray()) { result = EMPTY_JSON_ARRAY; } } return result; } public static void main(String[] args) { String str = "{\"id\": \"77555781-1bf7-4d58-b64e-3efd8a7ec6db\",\"wapstatus\": \"0\",\"name\": \" ???\",\"duration\": \"77\",\"url\": \"http://v.ifeng.com/ent/mingxing/201211/77555781-1bf7-4d58-b64e-3efd8a7ec6db.shtml\",\"img\": \"http://img.ifeng.com/itvimg//2012/11/30/16e9b832-162a-409c-9835-a9657ab26150.jpg\"}"; //EntityVideo entityVideo = GsonUtil.fromJson(str, EntityVideo.class); EntityVideo entity = GsonUtil.fromJson(str, EntityVideo.class); System.out.println(entity.toString()); } /** * * * @author kingzhu * */ public class EntityVideo { private String id; private String wapstatus; private String name; private String duration; private String url; private String img; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getWapstatus() { return wapstatus; } public void setWapstatus(String wapstatus) { this.wapstatus = wapstatus; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDuration() { return duration; } public void setDuration(String duration) { this.duration = duration; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String toString() { return ToStringBuilder.reflectionToString(this); } } }