您的位置:首页 > 编程语言 > Java开发

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

2017-08-07 21:28 483 查看
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类而来的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  json struts
相关文章推荐