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相反。
请看代码:
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;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值