当前位置: 代码迷 >> JavaScript >> Struts2+JSON+jQuery兑现异步交互数据时选择要序列化的属性(一注解方式转)
  详细解决方案

Struts2+JSON+jQuery兑现异步交互数据时选择要序列化的属性(一注解方式转)

热度:371   发布时间:2012-08-29 08:40:14.0
Struts2+JSON+jQuery实现异步交互数据时选择要序列化的属性(一注解方式转)

在使用Struts2的JSON插件,实现Action中的属性序列化成JSON对象时默认JSON插件会把所有Action中包含getter方法的属性都序列化到JSON对象中。但是有时候我们并不需要太多的属性,或者只需要一个属性。那么怎样控制属性序列化到JSON对象中哪?Struts2的JSON插件为我们提供了两种方式,第一:使用注解的方式控制,第二:使用Struts2的struts.xml配置文件的方式。

这一讲我们主要介绍注解方式。如果大家还不会Struts2+JSON+JQuery的交互方式请查看 http://zyw090111.iteye.com的Struts2+jQuery+JSON实现异步交互的文章

我们要使用JSON的注解是@JSON这个类共有是个属性分别是:
??? 1. name??? String 类型???? 用户为属性起一个别名(我们序列化到JSON对象中的键默认是属性名称,如果使用了name属性那么键是name起的名字);
??? 2. serialize? Boolean类型?? 默认为true 也就是可以被序列化,如果设为false那么该属性将不包含在JSON对象中;
??? 3. format? String类型? 主要是对日期进行格式化
??? 4. deserialize Boolean类型 默认为true,它是指反序列化,和serialize相反。
请看代码:

Java代码 复制代码?收藏代码
  1. package?test.json; ??
  2. ??
  3. import?java.util.Date; ??
  4. ??
  5. import?org.apache.struts2.json.annotations.JSON; ??
  6. ??
  7. import?com.opensymphony.xwork2.ActionSupport; ??
  8. ??
  9. @SuppressWarnings("serial") ??
  10. public?class?Users?extends?ActionSupport?{ ??
  11. ????private?int?id; ??
  12. ????private?String?userName; ??
  13. ????private?String?pwd; ??
  14. ????private?String?address; ??
  15. ????private?Date?birthday; ??
  16. ????public?int?getId()?{ ??
  17. ????????return?id; ??
  18. ????} ??
  19. ????public?void?setId(int?id)?{ ??
  20. ????????this.id?=?id; ??
  21. ????} ??
  22. ????@JSON(serialize=false) ??
  23. ????public?String?getUserName()?{ ??
  24. ????????return?userName; ??
  25. ????} ??
  26. ???? ??
  27. ????public?void?setUserName(String?userName)?{ ??
  28. ????????this.userName?=?userName; ??
  29. ????} ??
  30. ????@JSON(name="mm") ??
  31. ????public?String?getPwd()?{ ??
  32. ????????return?pwd; ??
  33. ????} ??
  34. ????public?void?setPwd(String?pwd)?{ ??
  35. ????????this.pwd?=?pwd; ??
  36. ????} ??
  37. ????public?String?getAddress()?{ ??
  38. ????????return?address; ??
  39. ????} ??
  40. ????public?void?setAddress(String?address)?{ ??
  41. ????????this.address?=?address; ??
  42. ????} ??
  43. ????@JSON(format="yy-MM-dd") ??
  44. ????public?Date?getBirthday()?{ ??
  45. ????????return?birthday; ??
  46. ????} ??
  47. ????public?void?setBirthday(Date?birthday)?{ ??
  48. ????????this.birthday?=?birthday; ??
  49. ????} ??
  50. ????@Override??
  51. ????public?String?execute()?throws?Exception?{ ??
  52. ???????? ??
  53. ????????this.id?=?10000; ??
  54. ????????this.userName?=?"zhangsan"; ??
  55. ????????this.pwd?=?"00000"; ??
  56. ????????this.address?=?"xian"; ??
  57. ????????this.birthday?=?new?Date(); ??
  58. ???????? ??
  59. ????????return?SUCCESS; ??
  60. ????} ??
  61. }??
  相关解决方案