fastjson的值过滤器ValueFilter

https://blog.csdn.net/linyifan_/article/details/83060408

原创林天乐 发布于2018-10-15 16:20:25 阅读数 1462  收藏
展开

项目中需要将前端传进的json数据清空值前后空格

两种实现方法

1.土方法 迭代trim()

  1.   RequestContext context = RequestContext.getCurrentContext();
  2.   InputStream in = (InputStream) context.get( “requestEntity”);
  3.   String body = StreamUtils.copyToString(in, Charset.forName( “UTF-8”));
  4.   JSONObject object = JSON.parseObject(body);
  5.   if (object == null) object = new JSONObject();
  6.   jsonParameterTrimObject(object);
  7.    
  8.   /**
  9.   * 清空JSONObject 值前后空格
  10.   * @param object
  11.   */
  12.   private void jsonParameterTrimObject(JSONObject object){
  13.   for(String str: object.keySet()){
  14.   Object o = object.get(str);
  15.   if(null != o){
  16.   if(o instanceof String){ //值为字符串类型
  17.   object.put(str,((String) o).trim()); //清空值前后空格
  18.   }
  19.   if(o instanceof JSONObject){ //值为JSON对象
  20.   jsonParameterTrimObject((JSONObject)o);
  21.   }
  22.   if(o instanceof JSONArray) { //值为JSON数组
  23.   jsonParameterTrimArray((JSONArray)o);
  24.   }
  25.   }
  26.   }
  27.   }
  28.    
  29.   /**
  30.   * 清空JSONArray 值前后空格
  31.   * @param array
  32.   */
  33.   private void jsonParameterTrimArray(JSONArray array){
  34.   if(array.size() > 0){
  35.   for(int i=0; i< array.size();i++){
  36.   Object oa = array.get(i);
  37.   if(null != oa){
  38.   if(oa instanceof String){ //值为字符串类型
  39.   array.set(i,((String) oa).trim()); //清空值前后空格
  40.   }
  41.   if(oa instanceof JSONObject){ //值为JSON对象
  42.   jsonParameterTrimObject((JSONObject)oa);
  43.   }
  44.   if(oa instanceof JSONArray) { //值为JSON数组
  45.   jsonParameterTrimArray((JSONArray)oa);
  46.   }
  47.   }
  48.   }
  49.   }
  50.   }

2.使用fastJson 值过滤器

  1.   package cango.scf.com.filter;
  2.    
  3.   import com.alibaba.fastjson.serializer.ValueFilter;
  4.    
  5.   public class SimpleValueFilter implements ValueFilter {
  6.   @Override
  7.   public Object process(Object object, String name, Object value) {
  8.   if (value instanceof String) {
  9.   value = ((String) value).trim();
  10.   }
  11.   return value;
  12.   }
  13.   }
  14.    
  15.   RequestContext context = RequestContext.getCurrentContext();
  16.   InputStream in = (InputStream) context.get( “requestEntity”);
  17.   if (in == null) {
  18.   in = context.getRequest().getInputStream();
  19.   }
  20.   String body = StreamUtils.copyToString(in, Charset.forName( “UTF-8”));
  21.   JSONObject object = JSON.parseObject(body);
  22.   if (object == null) object = new JSONObject();
  23.    
  24.   body = JSON.toJSONString(object, new SimpleValueFilter());