カスタム注記Jsonフィールドを無視(FastJson)

9649 ワード

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 
     * @return
     */
    public static  T toBean(String text, Class clazz) {
        return JSON.parseObject(text, clazz);
    }

    /**
     *      
     *
     * @param text
     * @param 
     * @return
     */
    public static  Object[] toArray(String text) {
        return toArray(text, null);
    }

    /**
     *      
     *
     * @param text
     * @param clazz
     * @param 
     * @return
     */
    public static  Object[] toArray(String text, Class clazz) {
        return JSON.parseArray(text, clazz).toArray();
    }

    /**
     *    List
     *
     * @param text
     * @param clazz
     * @param 
     * @return
     */
    public static  List toList(String text, Class 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 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

    
    
        
    


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