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的属性.

 

转载于:https://www.cnblogs.com/lsl0219/p/6441332.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值