java json过滤_JSONObject属性过滤 JSON序列化属性过滤

Java用JSONObject.fromObject()或者JSONArray.fromObject()的时候因为Bean的关联会出现很多错误,很多时候,我们也不需要一个Bean中所有的属性都序列化成Json数据格式,而fromObject默认是序列化所有的,因为我们需要过滤一些不常用或者不需要的属性。

package com.renyiwei.wydns.struts2.action.api;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;

import net.sf.json.JSONObject;

import net.sf.json.JsonConfig;

import net.sf.json.util.PropertyFilter;

import org.springframework.context.annotation.Scope;

import org.springframework.stereotype.Controller;

import com.renyiwei.wydns.domain.Client;

import com.renyiwei.wydns.service.ClientService;

import com.renyiwei.wydns.struts2.action.common.BaseAction;

@Scope("prototype")

@Controller("apiClientAction")

public class ClientAction extends BaseAction {

private String account;

@Resource

private ClientService clientService;

public String getAccount() {

return account;

}

public void setAccount(String account) {

this.account = account;

}

private JSONObject resultObj;

public JSONObject getResultObj() {

return resultObj;

}

public void setResultObj(JSONObject resultObj) {

this.resultObj = resultObj;

}

public String queryAjax() {

List clientList = clientService.getByLoginName(this.getAccount());

// 建一个json序列化的配置

JsonConfig config = new JsonConfig();

// 设置属性过滤 参数为实现了PropertyFilter接口的匿名内部类

config.setJsonPropertyFilter(new PropertyFilter() {

// 实现apply方法

public boolean apply(Object object, String property, Object value) {

if (object instanceof List || object instanceof Client || object instanceof Map || object instanceof String) {

if (object instanceof Client) {

if ("email".equals(property) || "phonenumber".equals(property) || "id".equals(property)) {

return false;

} else {

return true;

}

} else {

return false;

}

}

// false就是通过

return true;

}

});

Map resultMap = new HashMap();

resultMap.put("result", clientList);

// 序列化的时候把配置的config传进去

resultObj = JSONObject.fromObject(resultMap, config);

return SUCCESS;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值