Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。可以将一个 JSON 字符串转成一个 Java 对象,或者反过来。
?
Gson里最重要的对象有2个Gson 和 GsonBuilder
?
Gson有2个最基本的方法
1) toJson() – 转换java 对象到JSON
2) fromJson() – 转换JSON到java对象
实体类:
- 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?+?"]";??
- ????}??
- ??
- }??
测试类:
?
- <