Json排除指定字段小工具

json 时排除指定字段小工具1.0

demo:

	public static void main(String[] args) {
		TestJsonBean test = new TestJsonBean();
        Object s1 = objs2JsonExcludeField(test);
        System.out.println(s1);
    }
测试类:
import com.biligame.access.annotaition.ExcludeField;

import java.util.HashMap;

public class TestJsonBean {

    private int field1 = 1;

	/**
	 * 排除此字段
	 */
    @ExcludeField
    private String str1 = "123";

    private HashMap<Integer, Integer> map = new HashMap<>();

    {
        map.put(1, 1);
        map.put(2, 2);
    }


    public int getField1() {
        return field1;
    }

    public void setField1(int field1) {
        this.field1 = field1;
    }

    public String getStr1() {
        return str1;
    }

    public void setStr1(String str1) {
        this.str1 = str1;
    }

    public HashMap<Integer, Integer> getMap() {
        return map;
    }

    public void setMap(HashMap<Integer, Integer> map) {
        this.map = map;
    }
}
输出结果:

在这里插入图片描述

具体实现:

/**
 * @Author: xuanyu.liu
 * @Date: 2021/11/5 20:57
 * @Description: json时排除此字段
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcludeField {
    boolean isExclude() default true;
}
	/**
     * 外部调用的方法
     * @param object
     * @return
     * @throws IllegalAccessException
     */
    public static String obj2JsonUseExclude(Object object) throws IllegalAccessException {
        Object o = objs2JsonExcludeField(object);
        String resStr = null;
        if (o instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) o;
            resStr = jsonArray.toJSONString();
        } else {
            JSONObject jsonObject = (JSONObject) o;
            resStr = jsonObject.toJSONString();
        }
        return resStr;
    }
    /**
     * 1. 判断类型 list  or map(obj)  构建JSONArray  or JSONObject
     * 2. 如果存在子类型, 判断子类型,list or map  构建JSONArray  or JSONObject
     * 3. 判断exclude 标签
     * @param object
     * @return
     */
    private static Object objs2JsonExcludeField(Object object) throws IllegalAccessException {
        Object returnObj = null;
        if (object instanceof List) {
            JSONArray jsonArray = new JSONArray();
            List list = (List)object;
            for (Object obj : list) {
                Object s = objs2JsonExcludeField(obj);
                jsonArray.add(s);
            }
            returnObj = jsonArray;
        } else if (object instanceof Map) {
            returnObj = buildJsonObjByMap(object);
        } else {
            returnObj = buildJsonByObj(object);
        }

        return returnObj;
    }

    /**
     * 传入obj , 转出JSON
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    private static Object buildJsonByObj(Object obj) throws IllegalAccessException {
        JSONObject jsonObject = new JSONObject();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field f : fields) {
            f.setAccessible(true);
            ExcludeField excludeField = f.getAnnotation(ExcludeField.class);
            if (excludeField != null) {
                continue;
            }
            // 如果这个值是List 格式
            Object o = f.get(obj);
            Object sub = buildSubJsonObj(o);
            jsonObject.put(f.getName(), sub);
        }
        return jsonObject;
    }

    /**
     * 传入map , 转出JSON, 第一版只支持 String key
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    private static Object buildJsonObjByMap(Object obj) throws IllegalAccessException {
        JSONObject jsonObject = new JSONObject();
        Map map = (Map) obj;
        Iterator iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            // 只支持String key
            Object next = iterator.next();
            Object valObj = map.get(next);
            Object subValObj = buildSubJsonObj(valObj);
            jsonObject.put(String.valueOf(next), subValObj);

        }
        return jsonObject;
    }

    /**
     * 构建子JSON obj对象
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    private static Object buildSubJsonObj(Object obj) throws IllegalAccessException {
        boolean isBaseType = false;
        try {
            isBaseType = ((Class) obj.getClass().getField("TYPE").get(null)).isPrimitive();
        } catch (NoSuchFieldException e) {
            isBaseType = false;
        }
        boolean isOtherType = obj instanceof String;
        // 基础类型 或者其他指定类型
        if (isBaseType || isOtherType) {
            return obj;
        }
        // 其他的
        Object returnObj = objs2JsonExcludeField(obj);
        return returnObj;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值