Gson使用

之前写过一篇简单介绍Gson的文章,这两天在网上又找到一个很详细的工程,贴在下面。
gson:谷歌提供的JSON的解决方案。它的站点是http://code.google.com/p/google-gson/。
本人用过org.json和的JSON - lib中提供的解决方案。
先说下org.json,它属于轻量级的JSON的。它能够将Object或者ArrayList的转换为JSONObject的和JsonArrayList。但是在反转换的JSON字符串时却只能够提供字符串的结果。所以比较适合 开发者后期处理。
至于的JSON - lib的在反转方面做得比前者强了许多。它通过JSONObject.fromObject和JSONObject.toBean可以将Bean、ArrayList、HashMap中与JSONObject的互相转换。但是遇到嵌套问题

如一个Bean1->HashMap-> Bean2。当它对该对象反转换时将出现Bean2为JSONObject的对象的情况.

现在讲到gson了.它通过reflection来识别对象.见下面例子:

定义<Bean>
package org.gson.bean;

import java.util.Date;
import com.google.gson.annotations.Expose;
/** 
* 普通的UserBean 
*/ 
public class UserBean {
 @Expose
 //并不是java标准的注解,而是谷歌GSON的注解,表示它所注解的字段不支持序列化。
 private String id; 
 @Expose 
 private String name; 

 private Date birthday; 

 public String getId() { 
   return id; 
 } 

 public void setId(String id) { 
   this.id = id; 
 } 

 public String getName() { 
   return name; 
 } 

 public void setName(String name) { 
   this.name = name; 
 } 

 public Date getBirthday() { 
   return birthday; 
 } 

 public void setBirthday(Date birthday) { 
   this.birthday = birthday; 
 } 

 @Override 
 public String toString() { 
   return "UserBean [birthday=" + birthday + ", id=" + id + ", name=" 
     + name + "]"; 
 } 

}

--------------------------------------------------------------------------------
package org.gson.bean;

import java.util.List;
import java.util.Map;
/** 
 * 包含Arrylist和HashMap,里面保持UserBean 
 */ 
public class GroupBean {
 private String id; 
 private Map userMap; 
 private List userList; 

 public String getId() { 
   return id; 
 } 

 public void setId(String id) { 
   this.id = id; 
 } 

 public Map getUserMap() { 
   return userMap; 
 } 

 public void setUserMap(Map userMap) { 
   this.userMap = userMap; 
 } 

 public List getUserList() { 
   return userList; 
 } 

 public void setUserList(List userList) { 
   this.userList = userList; 
 } 

 @Override 
 public String toString() { 
   return "GroupBean [id=" + id + ", userList=" + userList + ", userMap=" 
     + userMap + "]"; 
 } 

}
---------------------------------------------------------------------------------------------- FilterAnnotationTest
package org.gson.main;

import org.gson.bean.UserBean;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/** 

 * 通過註釋過濾轉換對象 

 */ 

public class FilterAnnotationTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
    UserBean user = new UserBean(); 
    user.setId("1001"); 
    user.setName("张三"); 
    
    /** 
     *  设置注释过滤功能 
     *  Gson gson = new GsonBuilder() 
     *  .registerTypeAdapter(Id.class, new IdTypeAdapter()) 
     *  .serializeNulls() 
     *  .setDateFormat(DateFormat.LONG) 
      *  .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE) 
     *  .setPrettyPrinting() 
     *  .setVersion(1.0) 
     *  .create(); 
     */ 
    GsonBuilder builder = new GsonBuilder(); 
    // 不转换没有 @Expose 注解的字段 
    builder.excludeFieldsWithoutExposeAnnotation(); 
    Gson gson = builder.create(); 

    // 将JavaBean字符串转换为 JSON 
    String sUser = gson.toJson(user); 
    System.out.println(sUser); 
    // {"id":1001,"name":"张三"} 

    // 将JSON字符串转换为 JavaBean 
    UserBean user2 = gson.fromJson(sUser, UserBean.class); 
    System.out.println(user2.getId() + ", " + user2.getName()); 
    // 1001, 张三 
  } 

}


-------------------------------------------------------------------------------------------
package org.gson.main;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.gson.bean.UserBean;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/** 
* 模板反射對象Bean 
* @author yansheng 
*/ 

public class TemplateTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
    List<UserBean> testBeanList = new ArrayList<UserBean>(); 
    UserBean testBean = new UserBean(); 
    testBean.setId("1"); 
    testBean.setName("name"); 
    testBeanList.add(testBean); 
    
    Gson gson = new Gson(); 
    Type type = new TypeToken<List<UserBean>>(){}.getType(); 
    
    String beanListToJson = gson.toJson(testBeanList, type); 
    System.out.println(beanListToJson); 
    // prints [{"id":"id","name":"name"}] 

    List<UserBean> testBeanListFromJson = gson.fromJson(beanListToJson, type); 
    System.out.println(testBeanListFromJson); 
    // prints [TestBean@1ea5671[id=id,name=name,birthday=<null>]] 

 }

}

----------------------------------------------------------------------------
package org.gson.main;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/** 
* 簡單的集合使用 
* @author yansheng 
*/ 

public class SimpleCollectionTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
    Gson gson = new Gson(); 

    // 将ArrayList字符串转换为 JSON 
    List<String> testList = new ArrayList<String>(); 
    testList.add("first"); 
    testList.add("second"); 
    
    String listToJson = gson.toJson(testList); 
    System.out.println(listToJson); 
    // prints ["first","second"] 
    
    // 将JSON字符串转换为 ArrayList 
    List<String> testList2 = (List<String>) gson.fromJson(listToJson, new TypeToken<List<String>>(){}.getType()); 
    System.out.println(testList2); 
    
    // 将HashMap字符串转换为 JSON 
    Map<String, String> testMap = new HashMap<String, String>(); 
    testMap.put("id", "id.first"); 
    testMap.put("name", "name.second"); 
    
    String mapToJson = gson.toJson(testMap); 
    System.out.println(mapToJson); 
    // prints {"id":"id.first","name":"name.second"} 
    
    // 将JSON字符串转换为 HashMap 
    Map<String, String> userMap2 = (Map<String, String>) gson.fromJson(mapToJson, 
      new TypeToken<Map<String, String>>(){}.getType()); 
    System.out.println(userMap2.get("id")); 
    
 }

}

-------------------------------------------------------------------------
package org.gson.main;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.List;

import org.gson.bean.UserBean;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * 
 * date測試類
 */

public class DateTest {
 /**
  * 序列化方法
  * 
  * @param bean
  * @param type
  * @return
  */
 public static String bean2json(Object bean, Type type) {
  Gson gson = new GsonBuilder()
    .registerTypeAdapter(java.util.Date.class,
      new UtilDateSerializer())
    .setDateFormat(DateFormat.LONG).create();
  return gson.toJson(bean);
 }

 /**
  * 反序列化方法
  * 
  * @param json
  * @param type
  * @return
  */
 public static <T> T json2bean(String json, Type type) {
  Gson gson = new GsonBuilder()
    .registerTypeAdapter(java.util.Date.class,
      new UtilDateDeserializer())
    .setDateFormat(DateFormat.LONG).create();
  return gson.fromJson(json, type);
 }

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  List<UserBean> testBeanList = new ArrayList<UserBean>();
  UserBean testBean = new UserBean();
  testBean.setId("id");
  testBean.setName("name");
  testBean.setBirthday(new java.util.Date());
  testBeanList.add(testBean);

  java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<UserBean>>() {
  }.getType();
  String beanListToJson = bean2json(testBeanList, type);
  System.out.println("beanListToJson:" + beanListToJson);
  // prints [{"id":"id","name":"name","birthday":1256531559390}]

  List<UserBean> testBeanListFromJson = json2bean(beanListToJson, type);
  System.out.println(testBeanListFromJson);
  // prints [TestBean@77a7f9[id=id,name=name,birthday=Mon Oct 26 12:39:05
  // CST 2009]]

 }

}

--------------------------------------------------------------------
package org.gson.main;

import java.lang.reflect.Type;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

/**
 * 反串行Data
 */

public class UtilDateDeserializer implements JsonDeserializer<java.util.Date> {
 @Override
 public java.util.Date deserialize(JsonElement json, Type typeOfT,
   JsonDeserializationContext context) throws JsonParseException {
  return new java.util.Date(json.getAsJsonPrimitive().getAsLong());
 }
}

-----------------------------------------------------------
package org.gson.main;

import java.lang.reflect.Type;
import java.util.Date;

import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

/**
*  串行Data 
*/ 

public class UtilDateSerializer implements JsonSerializer<java.util.Date> {

 @Override
 public JsonElement serialize(Date src, Type typeOfSrc,
   JsonSerializationContext context) {
  // TODO Auto-generated method stub
  return new JsonPrimitive(src.getTime()); 
 }

}
package org.gson.main;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.gson.bean.GroupBean;
import org.gson.bean.UserBean;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/** 
* 嵌套使用對象Bean 
* @author yansheng 
*/ 

public class NestedTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
    UserBean user1 = new UserBean(); 
    user1.setId("1001"); 
    user1.setName("张三"); 
    
    UserBean user2 = new UserBean(); 
    user2.setId("1002"); 
    user2.setName("李四"); 
    
    Map userMap = new HashMap(); 
    userMap.put("user1", user1); 
    userMap.put("user2", user2); 
    
    List userList = new ArrayList(); 
    userList.add(user1); 
    userList.add(user2); 
    
    GroupBean groupBean = new GroupBean(); 
    groupBean.setId("1"); 
    groupBean.setUserMap(userMap); 
    groupBean.setUserList(userList); 
    
    Gson gson = new Gson(); 

    String sGroupBean = gson.toJson(groupBean, new TypeToken() { 
    }.getType()); 
    System.out.println(sGroupBean); 
    //{"id":"1","userMap":{"user2":{"id":"1002","name":"李四"},"user1":{"id":"1001","name":"张三"}},"userList":[{"id":"1001","name":"张三"},{"id":"1002","name":"李四"}]}

    // 将JSON字符串转换为 HashMap 
    GroupBean groupBean2 = (GroupBean) gson.fromJson(sGroupBean, 
      new TypeToken(){}.getType()); 
    System.out.println(groupBean2); 
    // 张三 

 }

}

GSONTest工程文件 BOX
GSON教程PDF BOX

Related Articles

Quote Of The Day