Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。可以将一个 JSON 字符串转成一个 Java 对象,或者反过来。
自我感觉Gson比其他工具要好用
jar和源码下载地址: http://code.google.com/p/google-gson/downloads/list
实体类:
package com.yuankai;
public class Person {
@Override
public String toString() {
// TODO Auto-generated method stub
return getName()+getAge();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
private String name;
private int age;
public Person(String name, int age) {
// System.out.println("construct 2");
this.age = age;
this.name = name;
}
public Person() {
// System.out.println("construct method");
}
}
测试类:
package com.yuankai;
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;
public class TestJson {
public static void main(String[] args) {
Gson g = new Gson();
Person p = new Person("guona", 55);
//Gson使用时,对象中可以不包含属性的getter和setter方法
System.out.println(g.toJson(p));
//Gson处理list
List<Person> l = new ArrayList();
l.add(new Person("yuankai", 21));
l.add(new Person("guona", 20));
System.out.println(g.toJson(l));
//Gson处理map
Map map = new HashMap();
map.put("name","ChenXiao");
map.put("sex","male");
map.put("age",23);
System.out.println(g.toJson(map));
//这个会调用Person的无参数构造方法
//当属性没有get或者set方法时也能给属性赋值
Person p1 = g.fromJson(g.toJson(p), Person.class);
System.out.println(p1);
List<Person> list =
g.fromJson(g.toJson(l),
new TypeToken<List<Person>>(){}.getType());
System.out.println(g.toJson(list));
//将json串转换为Map
Map<String,Object> map2 =
g.fromJson(g.toJson(map),
new TypeToken<Map<String,Object>>(){}.getType());
System.out.println(g.toJson(map2));
}
}
输出结果:
{"name":"guona","age":55}
[{"name":"yuankai","age":21},{"name":"guona","age":20}]
{"sex":"male","age":23,"name":"ChenXiao"}
guona55
[{"name":"yuankai","age":21},{"name":"guona","age":20}]
{"sex":"male","age":23.0,"name":"ChenXiao"}