class Person{ private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
public static void main(String[] args) { Person p=new Person(); JSONObject obj = JSONObject.fromObject(p); System.out.println(obj.toString()); }
运行上面的结果打印:
null
null
{"name":"","age":0}
发现当Integer 类型为null 最后是0,String 为null 最后是“”
从JsonObject的源码中可以找到如下代码:
我的jsonlib的版本是json-lib:jdk15:2.2.3 下面代码是从JsonObject的1037行开始
private static void setValue(JSONObject jsonObject,String key,Object value,Class type,JsonConfig jsonConfig) {
boolean accumulated = false;
if(value == null) {
value = jsonConfig.findDefaultValueProcessor(type).getDefaultValue(type);
if(!JsonVerifier.isValidJsonValue(value)) {
throw new JSONException("Value is not a valid JSON value. " + value);
}
}
当我的属性的值是null,就会通过 jsonConfig.findDefaultValueProcessor(type).getDefaultValue(type)获取对应的值。findDefaultValueProcessor()方法是
DefaultValueProcessor接口中方法,所以就需要我们自己创建DefaultValueProcessor的实现类修改默认值;
修改之后的代码:
public static void main(String[] args) { JsonConfig config=new JsonConfig(); config.registerDefaultValueProcessor(Double.class,new DefaultValueProcessor() { @Override public Object getDefaultValue(Class aClass) { return null; } }); config.registerDefaultValueProcessor(Integer.class,new DefaultValueProcessor() { @Override public Object getDefaultValue(Class aClass) { return null; } }); config.registerDefaultValueProcessor(Short.class,new DefaultValueProcessor() { @Override public Object getDefaultValue(Class aClass) { return null; } }); config.registerDefaultValueProcessor(Float.class,new DefaultValueProcessor() { @Override public Object getDefaultValue(Class aClass) { return null; } }); config.registerDefaultValueProcessor(Byte.class,new DefaultValueProcessor() { @Override public Object getDefaultValue(Class aClass) { return null; } }); config.registerDefaultValueProcessor(Long.class,new DefaultValueProcessor() { @Override public Object getDefaultValue(Class aClass) { return null; } }); config.registerDefaultValueProcessor(String.class,new DefaultValueProcessor() { @Override public Object getDefaultValue(Class aClass) { return null; } }); Person p=new Person(); JSONObject obj = JSONObject.fromObject(p,config); System.out.println(p.getName()); System.out.println(p.getAge()); System.out.println(obj.toString()); }
运行结果:
null null {"name":null,"age":null}
OK了原文链接:https://www.f2er.com/json/288817.html