下载地址:http://code.google.com/p/google-gson/downloads/list
API:http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html
在做android处理http请求中,大量使用了Google gson序列化对象、集合为json字符串向服务端传递数据,当然好处我就不废话了,注意事项:
值对象必须实现序列化接口,成员属性的名称必须与Json数据的key一致,建议遵从J2EE的标准,使用get-set方法控制属性的访问,因为Json的key是后台应用定义的,假如后台与前台的开发语言不同,命名规范也不一致,使用get-set能有效分离这些不规范的命名到其他模块代码中去。
下面摘抄下使用的方法:
网友的工具类:http://zhiweiofli.iteye.com/blog/1684236
/**
* Gson类库的封装工具类,专门负责解析json数据</br>
* 内部实现了Gson对象的单例
* @author zhiweiofli
* @version 1.0
* @since 2012-9-18
*/
public class JsonUtil {
private static Gson gson = null;
static {
if (gson == null) {
gson = new Gson();
}
}
private JsonUtil() {
}
/**
* 将对象转换成json格式
*
* @param ts
* @return
*/
public static String objectToJson(Object ts) {
String jsonStr = null;
if (gson != null) {
jsonStr = gson.toJson(ts);
}
return jsonStr;
}
/**
* 将对象转换成json格式(并自定义日期格式)
*
* @param ts
* @return
*/
public static String objectToJsonDateSerializer(Object ts,
final String dateformat) {
String jsonStr = null;
gson = new GsonBuilder()
.registerTypeHierarchyAdapter(Date.class,
new JsonSerializer<Date>() {
public JsonElement serialize(Date src,
Type typeOfSrc,
JsonSerializationContext context) {
SimpleDateFormat format = new SimpleDateFormat(
dateformat);
return new JsonPrimitive(format.format(src));
}
}).setDateFormat(dateformat).create();
if (gson != null) {
jsonStr = gson.toJson(ts);
}
return jsonStr;
}
/**
* 将json格式转换成list对象
*
* @param jsonStr
* @return
*/
public static List<?> jsonToList(String jsonStr) {
List<?> objList = null;
if (gson != null) {
java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<?>>() {
}.getType();
objList = gson.fromJson(jsonStr, type);
}
return objList;
}
/**
* 将json格式转换成list对象,并准确指定类型
* @param jsonStr
* @param type
* @return
*/
public static List<?> jsonToList(String jsonStr, java.lang.reflect.Type type) {
List<?> objList = null;
if (gson != null) {
objList = gson.fromJson(jsonStr, type);
}
return objList;
}
/**
* 将json格式转换成map对象
*
* @param jsonStr
* @return
*/
public static Map<?, ?> jsonToMap(String jsonStr) {
Map<?, ?> objMap = null;
if (gson != null) {
java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<Map<?, ?>>() {
}.getType();
objMap = gson.fromJson(jsonStr, type);
}
return objMap;
}
/**
* 将json转换成bean对象
*
* @param jsonStr
* @return
*/
public static Object jsonToBean(String jsonStr, Class<?> cl) {
Object obj = null;
if (gson != null) {
obj = gson.fromJson(jsonStr, cl);
}
return obj;
}
/**
* 将json转换成bean对象
*
* @param jsonStr
* @param cl
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T jsonToBeanDateSerializer(String jsonStr, Class<T> cl,
final String pattern) {
Object obj = null;
gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
public Date deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context)
throws JsonParseException {
SimpleDateFormat format = new SimpleDateFormat(pattern);
String dateStr = json.getAsString();
try {
return format.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}).setDateFormat(pattern).create();
if (gson != null) {
obj = gson.fromJson(jsonStr, cl);
}
return (T) obj;
}
/**
* 根据
*
* @param jsonStr
* @param key
* @return
*/
public static Object getJsonValue(String jsonStr, String key) {
Object rulsObj = null;
Map<?, ?> rulsMap = jsonToMap(jsonStr);
if (rulsMap != null && rulsMap.size() > 0) {
rulsObj = rulsMap.get(key);
}
return rulsObj;
}
}
引用方法:
(UserInfo)JsonUtil.jsonToBean(jsonString, UserInfo.
class
);
简单对象转化和带泛型的List转化
public class Student {
private int id;
private String name;
private Date birthDay;
public int getId() {
return id;
}
public void setId(int 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 "Student [birthDay=" + birthDay + ", id=" + id + ", name="
+ name + "]";
}
}
测试类:
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class GsonTest1 {
public static void main(String[] args) {
Gson gson = new Gson();
Student student1 = new Student();
student1.setId(1);
student1.setName("李坤");
student1.setBirthDay(new Date());
// //
System.out.println("----------简单对象之间的转化-------------");
// 简单的bean转为json
String s1 = gson.toJson(student1);
System.out.println("简单Bean转化为Json===" + s1);
// json转为简单Bean
Student student = gson.fromJson(s1, Student.class);
System.out.println("Json转为简单Bean===" + student);
// 结果:
// 简单Bean转化为Json==={"id":1,"name":"李坤","birthDay":"Jun 22, 2012 8:27:52 AM"}
// Json转为简单Bean===Student [birthDay=Fri Jun 22 08:27:52 CST 2012, id=1,
// name=李坤]
// //
Student student2 = new Student();
student2.setId(2);
student2.setName("曹贵生");
student2.setBirthDay(new Date());
Student student3 = new Student();
student3.setId(3);
student3.setName("柳波");
student3.setBirthDay(new Date());
List<Student> list = new ArrayList<Student>();
list.add(student1);
list.add(student2);
list.add(student3);
System.out.println("----------带泛型的List之间的转化-------------");
// 带泛型的list转化为json
String s2 = gson.toJson(list);
System.out.println("带泛型的list转化为json==" + s2);
// json转为带泛型的list
List<Student> retList = gson.fromJson(s2,
new TypeToken<List<Student>>() {
}.getType());
for (Student stu : retList) {
System.out.println(stu);
}
// 结果:
// 带泛型的list转化为json==[{"id":1,"name":"李坤","birthDay":"Jun 22, 2012 8:28:52 AM"},{"id":2,"name":"曹贵生","birthDay":"Jun 22, 2012 8:28:52 AM"},{"id":3,"name":"柳波","birthDay":"Jun 22, 2012 8:28:52 AM"}]
// Student [birthDay=Fri Jun 22 08:28:52 CST 2012, id=1, name=李坤]
// Student [birthDay=Fri Jun 22 08:28:52 CST 2012, id=2, name=曹贵生]
// Student [birthDay=Fri Jun 22 08:28:52 CST 2012, id=3, name=柳波]
}
}
当然开发中避免不了许多特殊的处理:
Gson注解和GsonBuilder
import java.util.Date;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Student {
private int id;
@Expose
private String name;
@Expose
@SerializedName("bir")
private Date birthDay;
public int getId() {
return id;
}
public void setId(int 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 "Student [birthDay=" + birthDay + ", id=" + id + ", name="
+ name + "]";
}
}
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
public class GsonTest2 {
public static void main(String[] args) {
//注意这里的Gson的构建方式为GsonBuilder,区别于test1中的Gson gson = new Gson();
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation() //不导出实体中没有用@Expose注解的属性
.enableComplexMapKeySerialization() //支持Map的key为复杂对象的形式
.serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss:SSS")//时间转化为特定格式
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)//会把字段首字母大写,注:对于实体上使用了@SerializedName注解的不会生效.
.setPrettyPrinting() //对json结果格式化.
.setVersion(1.0) //有的字段不是一开始就有的,会随着版本的升级添加进来,那么在进行序列化和返序列化的时候就会根据版本号来选择是否要序列化.
//@Since(版本号)能完美地实现这个功能.还的字段可能,随着版本的升级而删除,那么
//@Until(版本号)也能实现这个功能,GsonBuilder.setVersion(double)方法需要调用.
.create();
Student student1 = new Student();
student1.setId(1);
student1.setName("李坤");
student1.setBirthDay(new Date());
// //
System.out.println("----------简单对象之间的转化-------------");
// 简单的bean转为json
String s1 = gson.toJson(student1);
System.out.println("简单Bean转化为Json===" + s1);
// json转为简单Bean
Student student = gson.fromJson(s1, Student.class);
System.out.println("Json转为简单Bean===" + student);
// //
Student student2 = new Student();
student2.setId(2);
student2.setName("曹贵生");
student2.setBirthDay(new Date());
Student student3 = new Student();
student3.setId(3);
student3.setName("柳波");
student3.setBirthDay(new Date());
List<Student> list = new ArrayList<Student>();
list.add(student1);
list.add(student2);
list.add(student3);
System.out.println("----------带泛型的List之间的转化-------------");
// 带泛型的list转化为json
String s2 = gson.toJson(list);
System.out.println("带泛型的list转化为json==" + s2);
// json转为带泛型的list
List<Student> retList = gson.fromJson(s2,
new TypeToken<List<Student>>() {
}.getType());
for (Student stu : retList) {
System.out.println(stu);
}
}
}
结果:
----------简单对象之间的转化-------------
简单Bean转化为Json==={
"Name": "李坤",
"bir": "2012-06-22 21:26:40:592"
}
Json转为简单Bean===Student [birthDay=Fri Jun 22 21:26:40 CST 2012, id=0, name=李坤]
----------带泛型的List之间的转化-------------
带泛型的list转化为json==[
{
"Name": "李坤",
"bir": "2012-06-22 21:26:40:592"
},
{
"Name": "曹贵生",
"bir": "2012-06-22 21:26:40:625"
},
{
"Name": "柳波",
"bir": "2012-06-22 21:26:40:625"
}
]
Student [birthDay=Fri Jun 22 21:26:40 CST 2012, id=0, name=李坤]
Student [birthDay=Fri Jun 22 21:26:40 CST 2012, id=0, name=曹贵生]
Student [birthDay=Fri Jun 22 21:26:40 CST 2012, id=0, name=柳波]
Map处理
1:
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
}
import java.util.LinkedHashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
public class GsonTest3 {
public static void main(String[] args) {
Gson gson = new GsonBuilder().enableComplexMapKeySerialization()
.create();
Map<Point, String> map1 = new LinkedHashMap<Point, String>();// 使用LinkedHashMap将结果按先进先出顺序排列
map1.put(new Point(5, 6), "a");
map1.put(new Point(8, 8), "b");
String s = gson.toJson(map1);
System.out.println(s);// 结果:[[{"x":5,"y":6},"a"],[{"x":8,"y":8},"b"]]
Map<Point, String> retMap = gson.fromJson(s,
new TypeToken<Map<Point, String>>() {
}.getType());
for (Point p : retMap.keySet()) {
System.out.println("key:" + p + " values:" + retMap.get(p));
}
System.out.println(retMap);
System.out.println("----------------------------------");
Map<String, Point> map2 = new LinkedHashMap<String, Point>();
map2.put("a", new Point(3, 4));
map2.put("b", new Point(5, 6));
String s2 = gson.toJson(map2);
System.out.println(s2);
Map<String, Point> retMap2 = gson.fromJson(s2,
new TypeToken<Map<String, Point>>() {
}.getType());
for (String key : retMap2.keySet()) {
System.out.println("key:" + key + " values:" + retMap2.get(key));
}
}
}
结果:
[[{"x":5,"y":6},"a"],[{"x":8,"y":8},"b"]]
key:Point [x=5, y=6] values:a
key:Point [x=8, y=8] values:b
{Point [x=5, y=6]=a, Point [x=8, y=8]=b}
----------------------------------
{"a":{"x":3,"y":4},"b":{"x":5,"y":6}}
key:a values:Point [x=3, y=4]
key:b values:Point [x=5, y=6]
2:
import java.util.Date;
public class Student {
private int id;
private String name;
private Date birthDay;
public int getId() {
return id;
}
public void setId(int 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 "Student [birthDay=" + birthDay + ", id=" + id + ", name="
+ name + "]";
}
}
public class Teacher {
private int id;
private String name;
private String title;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return "Teacher [id=" + id + ", name=" + name + ", title=" + title
+ "]";
}
}
package com.tgb.lk.demo.gson.test4;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class GsonTest4 {
public static void main(String[] args) {
Student student1 = new Student();
student1.setId(1);
student1.setName("李坤");
student1.setBirthDay(new Date());
Student student2 = new Student();
student2.setId(2);
student2.setName("曹贵生");
student2.setBirthDay(new Date());
Student student3 = new Student();
student3.setId(3);
student3.setName("柳波");
student3.setBirthDay(new Date());
List<Student> stulist = new ArrayList<Student>();
stulist.add(student1);
stulist.add(student2);
stulist.add(student3);
Teacher teacher1 = new Teacher();
teacher1.setId(1);
teacher1.setName("米老师");
teacher1.setTitle("教授");
Teacher teacher2 = new Teacher();
teacher2.setId(2);
teacher2.setName("丁老师");
teacher2.setTitle("讲师");
List<Teacher> teacherList = new ArrayList<Teacher>();
teacherList.add(teacher1);
teacherList.add(teacher2);
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put("students", stulist);
map.put("teachers", teacherList);
Gson gson = new Gson();
String s = gson.toJson(map);
System.out.println(s);
System.out.println("----------------------------------");
Map<String, Object> retMap = gson.fromJson(s,
new TypeToken<Map<String, List<Object>>>() {
}.getType());
for (String key : retMap.keySet()) {
System.out.println("key:" + key + " values:" + retMap.get(key));
if (key.equals("students")) {
List<Student> stuList = (List<Student>) retMap.get(key);
System.out.println(stuList);
} else if (key.equals("teachers")) {
List<Teacher> tchrList = (List<Teacher>) retMap.get(key);
System.out.println(tchrList);
}
}
}
}
结果:
{"students":[{"id":1,"name":"李坤","birthDay":"Jun 22, 2012 9:48:19 PM"},{"id":2,"name":"曹贵生","birthDay":"Jun 22, 2012 9:48:19 PM"},{"id":3,"name":"柳波","birthDay":"Jun 22, 2012 9:48:19 PM"}],"teachers":[{"id":1,"name":"米老师","title":"教授"},{"id":2,"name":"丁老师","title":"讲师"}]}
----------------------------------
key:students values:[{id=1.0, name=李坤, birthDay=Jun 22, 2012 9:48:19 PM}, {id=2.0, name=曹贵生, birthDay=Jun 22, 2012 9:48:19 PM}, {id=3.0, name=柳波, birthDay=Jun 22, 2012 9:48:19 PM}]
[{id=1.0, name=李坤, birthDay=Jun 22, 2012 9:48:19 PM}, {id=2.0, name=曹贵生, birthDay=Jun 22, 2012 9:48:19 PM}, {id=3.0, name=柳波, birthDay=Jun 22, 2012 9:48:19 PM}]
key:teachers values:[{id=1.0, name=米老师, title=教授}, {id=2.0, name=丁老师, title=讲师}]
[{id=1.0, name=米老师, title=教授}, {id=2.0, name=丁老师, title=讲师}]