自定义注解忽略Json字段(FastJson)

/ FastJsonSpringJava / 2 条评论 / 1939浏览

#1. JSONFieldFilter

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by zxk175 on 17/5/20.
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface JSONFieldFilter {
    // 要处理的字段
    String[] fields();
}

#2. FastJsonUtil

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.JSONLibDataFormatSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.util.List;
import java.util.Map;

/**
 * Created by zxk175 on 17/5/7.
 */
public class FastJsonUtil {
    private static final SerializeConfig config;

    static {
        config = new SerializeConfig();
        // 使用和json-lib兼容的日期输出格式
        config.put(java.util.Date.class, new JSONLibDataFormatSerializer());
        // 使用和json-lib兼容的日期输出格式
        config.put(java.sql.Date.class, new JSONLibDataFormatSerializer());
        // 修改全局的全局日期格式
        JSON.DEFFAULT_DATE_FORMAT = SystemConstant.DATE_FORMAT_DEFAULT;
    }

    private static final SerializerFeature[] features = {
            // 输出key时是否使用双引号,默认为true
            SerializerFeature.QuoteFieldNames,
            // 避免循环引用
            SerializerFeature.DisableCircularReferenceDetect,
            // 是否输出值为null的字段
            SerializerFeature.WriteMapNullValue,
            // 数值字段如果为null,输出为0,而非null
            SerializerFeature.WriteNullNumberAsZero,
            // 字符类型字段如果为null,输出为"",而非null
            SerializerFeature.WriteNullStringAsEmpty,
            // list字段如果为null,输出为[],而非null
            SerializerFeature.WriteNullListAsEmpty,
            // boolean字段如果为null,输出为false,而非null
            SerializerFeature.WriteNullBooleanAsFalse,
            // 设置使用文本方式输出日期,fastjson默认是long
            SerializerFeature.WriteDateUseDateFormat,
            // 兼容IE6 即不将中文转为Unicode编码
            //SerializerFeature.BrowserCompatible
    };

    /**
     * Object转换为Json字符串, 使用默认配置
     *
     * @param object
     * @return
     */
    public static String toJSONNoFeatures(Object object) {
        return JSON.toJSONString(object, config, new FastJsonValueFilter());
    }

    /**
     * Object转换为Json字符串,使用自定义配置
     *
     * @param object
     * @return
     */
    public static String toJSONString(Object object) {
        return JSON.toJSONString(object, config, new FastJsonValueFilter(), features);
    }

    /**
     * Object转换为Json字符串,使用自定义配置
     *
     * @param object
     * @return
     */
    public static String toJSONString(Object object, SerializeFilter[] filters) {
        return JSON.toJSONString(object, config, filters, features);
    }

    /**
     * 转换为Object
     *
     * @param text
     * @return
     */
    public static Object toBean(String text) {
        return JSON.parse(text);
    }

    /**
     * 转换为指定Object
     *
     * @param text
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T toBean(String text, Class<T> clazz) {
        return JSON.parseObject(text, clazz);
    }

    /**
     * 转换为数组
     *
     * @param text
     * @param <T>
     * @return
     */
    public static <T> Object[] toArray(String text) {
        return toArray(text, null);
    }

    /**
     * 转换为数组
     *
     * @param text
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> Object[] toArray(String text, Class<T> clazz) {
        return JSON.parseArray(text, clazz).toArray();
    }

    /**
     * 转换为List
     *
     * @param text
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> toList(String text, Class<T> clazz) {
        return JSON.parseArray(text, clazz);
    }

    /**
     * javabean转化为序列化的json字符串
     *
     * @param object
     * @return
     */
    public static Object beanToJson(Object object) {
        String textJson = JSON.toJSONString(object, new FastJsonValueFilter(), features);
        Object objectJson = JSON.parse(textJson);
        return objectJson;
    }

    /**
     * string转化为序列化的json字符串
     *
     * @param text
     * @return
     */
    public static Object textToJson(String text) {
        Object objectJson = JSON.parse(text);
        return objectJson;
    }

    /**
     * json字符串转化为map
     *
     * @param s
     * @return
     */
    public static Map stringToMap(String s) {
        Map m = JSONObject.parseObject(s);
        return m;
    }

    /**
     * map转化为json字符串
     *
     * @param m
     * @return
     */
    public static String mapToString(Map m) {
        String s = JSONObject.toJSONString(m, new FastJsonValueFilter(), features);
        return s;
    }

    /**
     * 解析Json字符串
     *
     * @param jsonStr
     * @param key
     * @return
     */
    public static Object getJsonValueBykey(String jsonStr, String key) {
        JSONObject json = JSONObject.parseObject(jsonStr);
        return json.get(key);
    }
}

#3. FastJsonValueFilter

import com.alibaba.fastjson.serializer.ValueFilter;
import com.xiaoleilu.hutool.convert.Convert;
import com.xiaoleilu.hutool.util.ObjectUtil;

/**
 * Created by zxk175 on 17/5/7.
 */
public class FastJsonValueFilter implements ValueFilter {
    /**
     * 值过滤器 处理函数
     *
     * @param object
     * @param name
     * @param value
     * @return
     */
    @Override
    public Object process(Object object, String name, Object value) {

        if (ObjectUtil.isNull(value) && ("data".equals(name) || "extra".equals(name))) {
            return new Object();
        }

        if (ObjectUtil.isNull(value)) {
            return "";
        }

        // 防止Long转换为Json发生截断
        if (value instanceof Long) {
            value = Convert.toStr(value);
        }

        return value;
    }
}

#4. MethodReturnValueHandlerByJSON

import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.util.Set;

/**
 * Created by zxk175 on 17/5/20.
 */
public class MethodReturnValueHandlerByJSON implements HandlerMethodReturnValueHandler {
    /**
     * 检验是否支持本处理器处理,返回true会执行handleReturnValue方法
     *
     * @param returnType
     * @return
     */
    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        // 如果有自定义的JSONFieldFilter 注解 就用这个Handler 来处理
        return returnType.hasMethodAnnotation(JSONFieldFilter.class);
    }

    /**
     * 处理返回值的方法,returnValue即是controller方法中的返回值
     *
     * @param returnValue
     * @param returnType
     * @param mavContainer
     * @param webRequest
     * @throws Exception
     */
    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        // 设置这个就是最终的处理类了,处理完不再去找下一个类进行处理
        mavContainer.setRequestHandled(true);

        // 获得Response对象
        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        Annotation[] annotations = returnType.getMethodAnnotations();

        // 获取JSONFieldFilter
        JSONFieldFilter jsonFieldFilter = null;
        for (Annotation annotation : annotations) {
            if (annotation instanceof JSONFieldFilter) {
                jsonFieldFilter = (JSONFieldFilter) annotation;
            }
        }

        // 值过滤器
        FastJsonValueFilter vf = new FastJsonValueFilter();
        // 属性过滤器
        SimplePropertyPreFilter spp = new SimplePropertyPreFilter();
        // 要忽略属性数组
        String[] fields = jsonFieldFilter.fields();
        int len = fields.length;
        // 添加忽略属性
        if (len > 0) {
            Set<String> fieldSet = spp.getExcludes();
            for (int i = 0; i < len; i++) {
                fieldSet.add(fields[i]);
            }
        }
        // Json最大嵌套层级 --猜的
        spp.setMaxLevel(5);

        SerializeFilter[] filters = {vf, spp};

        String json = FastJsonUtil.toJSONString(returnValue, filters);
        response.getWriter().write(json);
    }
}

#5. spring-mvc.xml

<mvc:annotation-driven>
    <!-- 方法返回值处理器配置 -->
    <mvc:return-value-handlers>
        <bean class="MethodReturnValueHandlerByJSON"/>
    </mvc:return-value-handlers>
</mvc:annotation-driven>

#6. UserController

@JSONFieldFilter(fields = {
            "token", "createSource", "createTime",
            "updateTime", "status", "loginStatus",
            "verificationCode", "lastLoginTime", "lastLoginIp"
    })
    public ResponseVO userLoginV1(@PathVariable String mobile, @PathVariable String code, HttpServletRequest request) {
        return loginV1(mobile, code, request, true);
    }

#7. 注意

使用了自定义注解就不能用@ResponseBody
  1. 博主文章不错

    回复
    1. @月亮河博客

      谢谢!!!!

      回复