JSONObject属性过滤 JSON序列化属性过滤

By | 2015年2月11日

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;
    }
}

更新:通过注解实现JSONPropertyFilter