GSON是Google 提供的Json的解决方案。使用GSON需要下载jar包,下载地址:http://code.google.com/p/google-gson/,下载的Zip包中有GSON的help文档。org.json属于轻量级的JSON ,它能够将Object和ArrayList转化为JSonObject和JSonArraryList,但是在反转换的JSON字符串时却只能够提供字符串的结果。GSON能够将Bean Object转化为JSON,同时也能很好的将JSON转化为Bean Object.
一、创建一个普通的User Bean class,供后面使用。
import java.util.Date;
import com.google.gson.annotations.Expose;
/*一个普通的bean类*/
public class User {
@Expose
private String id; //Expose是Gson进行filter的标志
@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 "User [id= " + id + ", name= " + name + ",birthday= " + birthday
+ "]";
}
}
二、再创建一个 GroupBean class 为实现嵌套JSON。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GroupBean {
private String id;
private List<User> userList = new ArrayList<User>();
private Map<String, User> userMap = new HashMap<String, User>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
public Map<String, User> getUserMap() {
return userMap;
}
public void setUserMap(Map<String, User> userMap) {
this.userMap = userMap;
}
@Override
public String toString() {
return "GroupBean [id= " + id + "userList= " + userList + "userMap="
+ userMap + "]";
}
}
三、使用GSON对简单的List,Map的转换以及反转换
//简单的处理List、Map
private void TestGson1(){
Gson gson = new Gson();
List<String> strList = new ArrayList<String>();
strList.add("first");
strList.add("second");
strList.add("three");
String list2Json = gson.toJson(strList);
System.out.println("Simple List To JSON = " + list2Json);
List<String> json2List = gson.fromJson(list2Json, new TypeToken<List<String>>(){}.getType());
System.out.println("Simple JSon To List With GSON ");
for(String str:json2List){
System.out.println(str);
}
Map<String, String> strMap = new HashMap<String, String>();
strMap.put("frist", "Frist");
strMap.put("second", "Second");
strMap.put("three", "Three");
String map2Json = gson.toJson(strMap);
System.out.println("Simple Map To JSON = " + map2Json);
Map<String, String> json2Map = gson.fromJson(map2Json, new TypeToken<Map<String, String>>(){}.getType());
System.out.println("Simple JSon To Map With GSON ");
Set<String> keys = json2Map.keySet();
Iterator<String> iterator = keys.iterator();
while(iterator.hasNext()){
String key = iterator.next();
String value = json2Map.get(key);
System.out.println(key + " = " + value);
}
}
运行结果:
06-28 09:33:01.710: I/System.out(6294): Simple List To JSON = ["first","second","three"]
06-28 09:33:01.720: I/System.out(6294): Simple JSon To List With GSON
06-28 09:33:01.720: I/System.out(6294): first
06-28 09:33:01.720: I/System.out(6294): second
06-28 09:33:01.720: I/System.out(6294): three
06-28 09:33:01.730: I/System.out(6294): Simple Map To JSON = {"three":"Three","second":"Second","frist":"Frist"}
06-28 09:33:01.730: I/System.out(6294): Simple JSon To Map With GSON
06-28 09:33:01.730: I/System.out(6294): three = Three
06-28 09:33:01.730: I/System.out(6294): second = Second
06-28 09:33:01.730: I/System.out(6294): frist = Frist
四、针对有Annotation的Bean用GSON转换为JSON以及反转换
//设置过滤注解的
private void filterAnnotationTest(){
User user = new User();
user.setId("0001");
user.setName("ZhangSan");
GsonBuilder builder = new GsonBuilder();
// 不转换没有@Expose 注解的字段
builder.excludeFieldsWithoutExposeAnnotation();
Gson gson = builder.create();
//Bean to JSON
String bean2Json = gson.toJson(user);
System.out.println(bean2Json);
//JSON to Bean
User json2Bean = gson.fromJson(bean2Json, User.class);
System.out.println(json2Bean.toString());
}
运行结果:
06-28 09:33:01.740: I/System.out(6294): {"id":"0001","name":"ZhangSan"}
06-28 09:33:01.740: I/System.out(6294): User [id= 0001, name= ZhangSan,birthday= null]
五、使用GSON将List<Bea> to JSON 以及 JSON to List<Bean>
private void Test2(){
List<User> userList = new ArrayList<User>();
User user1 = new User();
user1.setId("0001");
user1.setName("Lisi");
userList.add(user1);
User user2 = new User();
user2.setId("0002");
user2.setName("Zhangsan");
userList.add(user2);
Gson gson = new Gson();
Type type = new TypeToken<List<User>>(){}.getType();
String bean2Json = gson.toJson(userList, type);
System.out.println("List Bean to Json = " + bean2Json);
List<User> json2Bean = gson.fromJson(bean2Json, type);
for(User user:json2Bean){
System.out.println(user);
}
}
运行结果:
06-28 09:33:01.750: I/System.out(6294): List Bean to Json = [{"id":"0001","name":"Lisi"},{"id":"0002","name":"Zhangsan"}]
06-28 09:33:01.750: I/System.out(6294): User [id= 0001, name= Lisi,birthday= null]
06-28 09:33:01.750: I/System.out(6294): User [id= 0002, name= Zhangsan,birthday= null]
六、使用GSON对嵌套Bean解析
private void Test3(){
System.out.println("Test3");
User user1 = new User();
user1.setId("0001");
user1.setName("Lisi");
User user2 = new User();
user2.setId("0002");
user2.setName("Zhangsan");
Map<String, User> map = new HashMap<String, User>();
map.put("user1", user1);
map.put("user2", user2);
List<User> userList = new ArrayList<User>();
userList.add(user1);
userList.add(user2);
GroupBean groupBean = new GroupBean();
groupBean.setId("1");
groupBean.setUserList(userList);
groupBean.setUserMap(map);
Gson gson = new Gson();
Type type = new TypeToken<GroupBean>(){}.getType();
String bean2Json = gson.toJson(groupBean, type);
System.out.println("Json = " + bean2Json);
GroupBean bean = gson.fromJson(bean2Json, type);
System.out.println("id = "+bean.getId());
for(User usr:bean.getUserList()){
System.out.println(usr);
}
Set<String> keys = bean.getUserMap().keySet();
Iterator<String> iterator = keys.iterator();
while(iterator.hasNext()){
String key = iterator.next();
User value = bean.getUserMap().get(key);
System.out.println(key + " = " + value);
}
}
运行结果:
06-28 09:33:01.750: I/System.out(6294): Test3
06-28 09:33:01.760: I/System.out(6294): Json = {"id":"1","userList":[{"id":"0001","name":"Lisi"},{"id":"0002","name":"Zhangsan"}],"userMap":{"user2":{"id":"0002","name":"Zhangsan"},"user1":{"id":"0001","name":"Lisi"}}}
06-28 09:33:01.760: I/System.out(6294): id = 1
06-28 09:33:01.760: I/System.out(6294): User [id= 0001, name= Lisi,birthday= null]
06-28 09:33:01.760: I/System.out(6294): User [id= 0002, name= Zhangsan,birthday= null]
06-28 09:33:01.760: I/System.out(6294): user2 = User [id= 0002, name= Zhangsan,birthday= null]
06-28 09:33:01.760: I/System.out(6294): user1 = User [id= 0001, name= Lisi,birthday= null]
七、Date类需要Serializer和Deserializer,需要implement GSON的JsonDeserializer<java.util.Date> 和JsonSerializer<java.util.Date>
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;
public class UtilDateSerializer implements JsonSerializer<java.util.Date> {
@Override
public JsonElement serialize(Date arg0, Type arg1,
JsonSerializationContext arg2) {
// TODO Auto-generated method stub
return new JsonPrimitive(arg0.getTime());
}
}
import java.lang.reflect.Type;
import java.util.Date;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
/*
* Date反串行
*/
public class UtilDateDeserializer implements JsonDeserializer<java.util.Date> {
@Override
public Date deserialize(JsonElement arg0, Type arg1,
JsonDeserializationContext arg2) throws JsonParseException {
// TODO Auto-generated method stub
return new java.util.Date(arg0.getAsJsonPrimitive().getAsLong());
}
}
import java.lang.reflect.Type;
import java.text.DateFormat;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JsonForDate {
/**
* 序列化方法
*
* @param bean
* @param type
* @return
*/
public static String bean2Json(Object object, Type type) {
Gson gson = new GsonBuilder()
.registerTypeAdapter(java.util.Date.class,
new UtilDateSerializer())
.setDateFormat(DateFormat.LONG).create();
return gson.toJson(object);
}
/**
* 反序列化方法
*
* @param bean
* @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);
}
}
八、测试Date
private void JsonTestWithDate(){
System.out.println("JsonTestWithDate");
List<User> userList = new ArrayList<User>();
User user1 = new User();
user1.setId("0001");
user1.setName("Lisi");
user1.setBirthday(new java.util.Date());
User user2 = new User();
user2.setId("0002");
user2.setName("Zhangsan");
user2.setBirthday(new java.util.Date());
userList.add(user1);
userList.add(user2);
Type type = new TypeToken<List<User>>(){}.getType();
String json = JsonForDate.bean2Json(userList, type);
System.out.println(json);
List<User> json2Bean = JsonForDate.json2bean(json, type);
for(User user:json2Bean){
System.out.println(user);
}
}
运行结果:
06-28 09:33:01.760: I/System.out(6294): JsonTestWithDate
06-28 09:33:01.780: I/System.out(6294): [{"birthday":1372383181769,"id":"0001","name":"Lisi"},{"birthday":1372383181769,"id":"0002","name":"Zhangsan"}]
06-28 09:33:01.780: I/System.out(6294): User [id= 0001, name= Lisi,birthday= Fri Jun 28 09:33:01 格林尼治标准时间+0800 2013]
06-28 09:33:01.780: I/System.out(6294): User [id= 0002, name= Zhangsan,birthday= Fri Jun 28 09:33:01 格林尼治标准时间+0800 2013]