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,
// 避免循環(huán)引用
SerializerFeature.DisableCircularReferenceDetect,
// 是否輸出值為null的字段
SerializerFeature.WriteMapNullValue,
// 數(shù)值字段如果為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);
}
/**
* 轉換為數(shù)組
*
* @param text
* @param <T>
* @return
*/
public static <T> Object[] toArray(String text) {
return toArray(text, null);
}
/**
* 轉換為數(shù)組
*
* @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 {
/**
* 值過濾器 處理函數(shù)
*
* @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發(fā)生截斷
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會執(zhí)行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();
// 要忽略屬性數(shù)組
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