清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>
gson是一个json库,它可以方便的转换java bean成json对象,也可以方便的将json对象转换为java bean。
比起官方的Lib,Gson除了提供原本的Json相关功能外,更包含了Json和Java Object的互相转换,而且许多常见的类型也可以转换,特別是collection集合,非常方便
其项目地址:https://code.google.com/p/google-gson/
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class People {
private int id;
private String name;
private float height;
private double weight;
private List friends = new ArrayList();
private Map info = new HashMap();
private Date birthday;
private String comment;
public People(){
id = 123456;
name = "Jacky";
height = new Float(172.2);
weight = new Double(61.236);
friends.add("Sam");
friends.add("Jimmy");
info.put("country","Taiwan");
info.put("city","Taipei");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
birthday = sdf.parse("1989-08-09");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
comment = null;
}
public String toString(){
String str = "";
str += "id="+id;
str += " name="+name;
str += " height="+height;
str += " weight="+weight;
str += " ...etc";
return str;
}
public static void main(String[] args) {
People p = new People();
//Gson gson = new Gson();
//If you wanna allow null object
Gson gson = new GsonBuilder().serializeNulls().create();
String str = gson.toJson(p);
System.out.println(str);
People p2 = gson.fromJson(str, People.class);
System.out.println(p2.toString());
}
}