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类而来的。

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

猜你喜欢

转载自blog.csdn.net/qq_31803503/article/details/76861680