在使用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相反。
请看代码:
- package?test.json; ??
- ??
- import?java.util.Date; ??
- ??
- import?org.apache.struts2.json.annotations.JSON; ??
- ??
- import?com.opensymphony.xwork2.ActionSupport; ??
- ??
- @SuppressWarnings("serial") ??
- public?class?Users?extends?ActionSupport?{ ??
- ????private?int?id; ??
- ????private?String?userName; ??
- ????private?String?pwd; ??
- ????private?String?address; ??
- ????private?Date?birthday; ??
- ????public?int?getId()?{ ??
- ????????return?id; ??
- ????} ??
- ????public?void?setId(int?id)?{ ??
- ????????this.id?=?id; ??
- ????} ??
- ????@JSON(serialize=false) ??
- ????public?String?getUserName()?{ ??
- ????????return?userName; ??
- ????} ??
- ???? ??
- ????public?void?setUserName(String?userName)?{ ??
- ????????this.userName?=?userName; ??
- ????} ??
- ????@JSON(name="mm") ??
- ????public?String?getPwd()?{ ??
- ????????return?pwd; ??
- ????} ??
- ????public?void?setPwd(String?pwd)?{ ??
- ????????this.pwd?=?pwd; ??
- ????} ??
- ????public?String?getAddress()?{ ??
- ????????return?address; ??
- ????} ??
- ????public?void?setAddress(String?address)?{ ??
- ????????this.address?=?address; ??
- ????} ??
- ????@JSON(format="yy-MM-dd") ??
- ????public?Date?getBirthday()?{ ??
- ????????return?birthday; ??
- ????} ??
- ????public?void?setBirthday(Date?birthday)?{ ??
- ????????this.birthday?=?birthday; ??
- ????} ??
- ????@Override??
- ????public?String?execute()?throws?Exception?{ ??
- ???????? ??
- ????????this.id?=?10000; ??
- ????????this.userName?=?"zhangsan"; ??
- ????????this.pwd?=?"00000"; ??
- ????????this.address?=?"xian"; ??
- ????????this.birthday?=?new?Date(); ??
- ???????? ??
- ????????return?SUCCESS; ??
- ????} ??
- }??