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

Json转换利器Gson之实例三-Map处理(上)

Map的存储结构式Key/Value形式,Key 和 Value可以是普通类型,也可以是自己写的JavaBean(本文),还可以是带有泛型的List(下一篇博客).本例中您要重点看如何将Json转回为普通JavaBean对象时TypeToken的定义.

?

实体类:

?

?

?

  1. public?class?Point?{??
  2. ????private?int?x;??
  3. ????private?int?y;??
  4. ??
  5. ????public?Point(int?x,?int?y)?{??
  6. ????????this.x?=?x;??
  7. ????????this.y?=?y;??
  8. ????}??
  9. ??
  10. ????public?int?getX()?{??
  11. ????????return?x;??
  12. ????}??
  13. ??
  14. ????public?void?setX(int?x)?{??
  15. ????????this.x?=?x;??
  16. ????}??
  17. ??
  18. ????public?int?getY()?{??
  19. ????????return?y;??
  20. ????}??
  21. ??
  22. ????public?void?setY(int?y)?{??
  23. ????????this.y?=?y;??
  24. ????}??
  25. ??
  26. ????@Override??
  27. ????public?String?toString()?{??
  28. ????????return?"Point?[x="?+?x?+?",?y="?+?y?+?"]";??
  29. ????}??
  30. ??
  31. }??


测试类:

?

?

  1. import?java.util.LinkedHashMap;??
  2. import?java.util.Map;??
  3. ??
  4. import?com.google.gson.Gson;??
  5. import?com.google.gson.GsonBuilder;??
  6. import?com.google.gson.reflect.TypeToken;??
  7. ??
  8. public?class?GsonTest3?{??
  9. ??
  10. ????