Struts2 return JSON data and convert the date field

Configure the struts.xml to support return JSON data

The package must extends

struts-default,json-default

Must define below result

<result name="success" type="json">
    <param name="root">dataMap</param>
</result>

Sample configuration in struts.xml

<package extends="struts-default,json-default" name="friendLink" namespace="/friendLink">
        <action class="friendLinkAction" method="{1}" name="friendLink_*">
            <result name="success" type="json">
                <param name="root">dataMap</param>
            </result>
        </action>
 </package>

Your action java class must define below property

private Map<String, Object> dataMap = new HashMap<String, Object>();
public Map<String, Object> getDataMap() {
    return dataMap;
}
public void setDataMap(Map<String, Object> dataMap) {
    this.dataMap = dataMap;
}

Sample code in action class

public void login(){
    dataMap.put("status", 200);
    dataMap.put("message", "login success");
    return "success";
}
// The client side will receive the JSON data
//{"status":200, "message":"login success"}

Add JSON annotation to convert the date field

Default the date may show like 2016-01-01T12:45:12
You can add @JSON(format=”yyyy-MM-dd HH:mm:ss”) or @JSON(format=”yyyy-MM-dd”) to the getter method
Sample code show below:

import org.apache.struts2.json.annotations.JSON;

@JSON(format="yyyy-MM-dd HH:mm:ss")
public Date getCreationDate() {
    return creationDate;
}

Reference

Related Jars:

struts2-json-plugin-2.3.28.1.jar
struts2-core-2.3.28.1.jar
jackson-databind-2.6.4.jar
jackson-core-2.6.4.jar
jackson-annotations-2.6.4.jar
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值