fastjson的值过滤器ValueFilter
项目中需要将前端传进的json数据清空值前后空格
两种实现方法
1.土方法 迭代trim()
-
RequestContext context = RequestContext.getCurrentContext();
-
InputStream in = (InputStream) context.get("requestEntity");
-
String body = StreamUtils.copyToString(in, Charset.forName("UTF-8"));
-
JSONObject object = JSON.parseObject(body);
-
if (object == null) object = new JSONObject();
-
jsonParameterTrimObject(object);
-
-
/**
-
* 清空JSONObject 值前后空格
-
* @param object
-
*/
-
private void jsonParameterTrimObject(JSONObject object){
-
for(String str: object.keySet()){
-
Object o = object.get(str);
-
if(null != o){
-
if(o instanceof String){ //值为字符串类型
-
object.put(str,((String) o).trim()); //清空值前后空格
-
}
-
if(o instanceof JSONObject){ //值为JSON对象
-
jsonParameterTrimObject((JSONObject)o);
-
}
-
if(o instanceof JSONArray) { //值为JSON数组
-
jsonParameterTrimArray((JSONArray)o);
-
}
-
}
-
}
-
}
-
-
/**
-
* 清空JSONArray 值前后空格
-
* @param array
-
*/
-
private void jsonParameterTrimArray(JSONArray array){
-
if(array.size() > 0){
-
for(int i=0; i< array.size();i++){
-
Object oa = array.get(i);
-
if(null != oa){
-
if(oa instanceof String){ //值为字符串类型
-
array.set(i,((String) oa).trim()); //清空值前后空格
-
}
-
if(oa instanceof JSONObject){ //值为JSON对象
-
jsonParameterTrimObject((JSONObject)oa);
-
}
-
if(oa instanceof JSONArray) { //值为JSON数组
-
jsonParameterTrimArray((JSONArray)oa);
-
}
-
}
-
}
-
}
-
}
2.使用fastJson 值过滤器
-
package cango.scf.com.filter;
-
-
import com.alibaba.fastjson.serializer.ValueFilter;
-
-
public class SimpleValueFilter implements ValueFilter {
-
-
public Object process(Object object, String name, Object value) {
-
if (value instanceof String) {
-
value = ((String) value).trim();
-
}
-
return value;
-
}
-
}
-
-
RequestContext context = RequestContext.getCurrentContext();
-
InputStream in = (InputStream) context.get("requestEntity");
-
if (in == null) {
-
in = context.getRequest().getInputStream();
-
}
-
String body = StreamUtils.copyToString(in, Charset.forName("UTF-8"));
-
JSONObject object = JSON.parseObject(body);
-
if (object == null) object = new JSONObject();
-
-
body = JSON.toJSONString(object, new SimpleValueFilter());