json序列化返回到页面
用json过滤掉不需要序列化的属性 。解决Refrence和LazyLoading引起的死循环问题 。
这里用阿里巴巴的fastjson会更方便,性能更好。当返回的是一个对象,或集合,需要序列化回显到页面的,以返回list为例
举个例子:
//将list数据序列化为json格式数据,返回到客户端浏览器
public void writeList2json(List list, final String[] excludes) {
PropertyFilter propertyFilter = new PropertyFilter() {
@Override
public boolean apply(Object object, String name, Object value) {
// TODO Auto-generated method stub
for (String string : excludes) {
if(name.equalsIgnoreCase(string)){
return false;
}
}
return true ;
}
};
String json = JSON.toJSONString(list,propertyFilter,
SerializerFeature.DisableCircularReferenceDetect);
ServletActionContext.getResponse().setContentType(
"text/json;charset=UTF-8");
try {
ServletActionContext.getResponse().getWriter().print(json);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这里用PropertyFilter(属性过滤器,过滤掉不需要的返回的数据)
实体类需要实现Serializable接口
package cn.itcast.crm.domain;
import java.io.Serializable;
public class Customer implements Serializable {
private Integer id;
private String name;
private String station;
private String telephone;
private String address;
private String decidedzone_id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStation() {
return station;
}
@JSONField(serialize=false)
public void setStation(String station) {
this.station = station;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDecidedzone_id() {
return decidedzone_id;
}
public void setDecidedzone_id(String decidedzone_id) {
this.decidedzone_id = decidedzone_id;
}
}
可以通过在需要过滤的属性上加@JSONField(serialize=false)注解。也可以通过在调用方法排除不需要序列化的属性
public String findCustomersAssociation(){
List<Customer> list = customerService.findhasassociationCustomers(model.getId());
String[] excludes = new String[]{"station","telephone","address","decidedzone_id"};
this.writeList2json(list, excludes);
return NONE;
}
fastjson已经处理了懒加载引起的死循环问题。如果是用的jsonlib,就需要在实体类的映射文件中,<many-to-one>标签中加一个lazy=false的属性.