今天写东西,发现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