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

Json转换利器Gson之实例二-Gson注解和GsonBuilder

有时候我们不需要把实体的所有属性都导出,只想把一部分属性导出为Json.

?

有时候我们的实体类会随着版本的升级而修改.

?

有时候我们想对输出的json默认排好格式.

?

... ...

?

请看下面的例子吧:

?

实体类:

?

  1. import?java.util.Date;??
  2. ??
  3. import?com.google.gson.annotations.Expose;??
  4. import?com.google.gson.annotations.SerializedName;??
  5. ??
  6. public?class?Student?{??
  7. ????private?int?id;??
  8. ??????
  9. ????@Expose??
  10. ????private?String?name;??
  11. ??????
  12. ????@Expose??
  13. ????@SerializedName("bir")??
  14. ????private?Date?birthDay;??
  15. ??
  16. ????public?int?getId()?{??
  17. ????????return?id;??
  18. ????}??
  19. ??
  20. ????public?void?setId(int?id)?{??
  21. ????????this.id?=?id;??
  22. ????}??
  23. ??
  24. ????public?String?getName()?{??
  25. ????????return?name;??
  26. ????}??
  27. ??
  28. ????public?void?setName(String?name)?{??
  29. ????????this.name?=?name;??
  30. ????}??
  31. ??
  32. ????public?Date?getBirthDay()?{??
  33. ????????return?birthDay;??
  34. ????}??
  35. ??
  36. ????public?void?setBirthDay(Date?birthDay)?{??
  37. ????????this.birthDay?=?birthDay;??
  38. ????}??
  39. ??
  40. ????@Override??
  41. ????public?String?toString()?{??
  42. ????????return?"Student?[birth