日期:2014-05-16  浏览次数:20366 次

Json转换利器Gson之实例一-简单对象转化和带泛型的List转化

Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。可以将一个 JSON 字符串转成一个 Java 对象,或者反过来。

?

Gson里最重要的对象有2个Gson 和 GsonBuilder

?

Gson有2个最基本的方法
1) toJson() – 转换java 对象到JSON
2) fromJson() – 转换JSON到java对象


实体类:


  1. public?class?Student?{??
  2. ????private?int?id;??
  3. ????private?String?name;??
  4. ????private?Date?birthDay;??
  5. ??
  6. ????public?int?getId()?{??
  7. ????????return?id;??
  8. ????}??
  9. ??
  10. ????public?void?setId(int?id)?{??
  11. ????????this.id?=?id;??
  12. ????}??
  13. ??
  14. ????public?String?getName()?{??
  15. ????????return?name;??
  16. ????}??
  17. ??
  18. ????public?void?setName(String?name)?{??
  19. ????????this.name?=?name;??
  20. ????}??
  21. ??
  22. ????public?Date?getBirthDay()?{??
  23. ????????return?birthDay;??
  24. ????}??
  25. ??
  26. ????public?void?setBirthDay(Date?birthDay)?{??
  27. ????????this.birthDay?=?birthDay;??
  28. ????}??
  29. ??
  30. ????@Override??
  31. ????public?String?toString()?{??
  32. ????????return?"Student?[birthDay="?+?birthDay?+?",?id="?+?id?+?",?name="??
  33. ????????????????+?name?+?"]";??
  34. ????}??
  35. ??
  36. }??


测试类:

?

?
  1. <