Java代码
import java.util.Iterator;
import java.util.Collection;
import java.util.Enumeration;
import java.lang.reflect.Type;
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;
/**
* 包含操作 {@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>。下面是工具类的使用案例:
* </p>
*
* <pre>
* public class User {
* {@literal @SerializedName("pwd")}
* private String password;
* {@literal @Expose}
* {@literal @SerializedName("uname")}
* private String username;
* {@literal @Expose}
* {@literal @Since(1.1)}
* private String gender;
* {@literal @Expose}
* {@literal @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
* @version 1.0, 2009-6-27
*/
public class JSONUtils extends Utils {
@SuppressWarnings("unused")
private static final Log log = LogFactory.getLog(JSONUtils.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} 的 {@literal @Since} 注解常用的版本号常量 - {@code 1.0}。 */
public static final Double SINCE_VERSION_10 = 1.0d;