struts2注解返回json串实现方式(序列化对象属性输出)

1.想要struts2返回json串,必须引入struts2-json-plugin-2.3.4.1.jar

2.继承json-default包

 

@Component
@Scope("prototype")
@ParentPackage("json-default")
@Namespace("/tax/test")
@Results({
	@Result(name="jsonList", type = "json", params = {"root", "personList")
})
public class TestAction extends ActionSupport {
	List<Person> personList = new ArrayList<Person>(0);
	@Action("test")
	public String test(){
		String result = "";
		result = "jsonList";
		try {
			for (int i = 0; i < 5; i++) {
				Person person = new Person(1l,"小明"+i,14l);//Person属性:eid,name,age
				personList.add(person);
			}
			System.out.println(personList.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;  
	}}


当然personList需要get/set方法。

 

 

当我们想要个别字段转换json串时,如何实现呢?

很简单,直接上源码:

 

@Component
@Scope("prototype")
@ParentPackage("json-default")
@Namespace("/tax/test")
@Results({
	@Result(name="jsonList", type = "json", params = {"root", "personList", "includeProperties", "\\[\\d+\\], .*eid, .*name"})
})
public class TestAction extends ActionSupport {
	List<Person> personList = new ArrayList<Person>(0);
	@Action("test")
	public String test(){
		String result = "";
		result = "jsonList";
		try {
			for (int i = 0; i < 5; i++) {
				Person person = new Person(1l,"小明"+i,14l);//Person属性:eid(int),name(String),age(int)
				personList.add(person);
			}
			System.out.println(personList.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;  
	}}

另外如果输出的对象有继承父类,而我们想要输出父类属性时,可以添加“ignoreHierarchy”,“false”

 

 

@Result(name="jsonList2", type = "json", params = {"root", "studentList", "ignoreHierarchy", "false", "includeProperties", "\\[\\d+\\], .*eid, .*name, .*subect"}),

 

subect是Student类的属性,而eid,name则继承Person类而来的。

感兴趣的朋友可以关注微信公众号(会定时推送新的知识):

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值