• json不转化值是null的字段


      今天写东西,发现JSONObject.fromObject(),方法,会把value是null的字段,转为0或"",就自己写了一个方法,如果value是null就不转换

      

    package com.moji.feedstreamapplet.util;
    
    import java.lang.reflect.Field;
    
    import com.moji.feedstreamapplet.bean.ExpandParam;
    
    import net.sf.json.JSONObject;
    
    public class JsonUtil {
        
        public static JSONObject jsonObjectFromBean(Object obj){
            String className = obj.getClass().toString().split(" ")[1];
            JSONObject jsonObj = new JSONObject();
            try {
                Class<?> c = Class.forName(className);
                
                Field[] fields = c.getDeclaredFields();
            
                for(Field field : fields){
                    field.setAccessible(true);
                    Object val = field.get(obj);
                    if(val != null && !val.toString().isEmpty()){
                        jsonObj.put(field.getName(), val);
                    }
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            
            return jsonObj;
        }
        
        public static void main(String[] args) {
            ExpandParam ep = new ExpandParam();
            ep.setDelete("1");
            ep.setImageNumber(23);
            ep.setIsCaputer(null);
            JSONObject jsonObj = JsonUtil.jsonObjectFromBean(ep);
            System.out.println(jsonObj);
        }
    }

    另一个方法:

            JsonConfig config = new JsonConfig(); 
            config.setJsonPropertyFilter(new PropertyFilter() {
                
                @Override
                public boolean apply(Object source, String name, Object value) {
                    if (value == null || "".equals(value)) {
                        return true;
                    }
                    return false;
                }
            });
            SONObject.fromObject(param,config);

    就是JasonConfig

  • 相关阅读:
    爬虫实战篇(模拟登录)---我们以模拟去哪儿网为例
    requests库详解
    爬取拉钩网职位信息写入mongodb数据库(小白学爬虫--实战篇1)
    《Vue项目关于i18n双语切换》
    《Vue+Vuetify》
    《Vue项目的创建以及初始化(两种方法)》
    《关于Vue的涟漪点击》
    《Vue的父子组件传值》
    《vue 页面进出类似APP的滑动效果》
    《Vue里的路由拦截》
  • 原文地址:https://www.cnblogs.com/fubaizhaizhuren/p/5465569.html
Copyright © 2020-2023  润新知