针对这一情况。
我用的json转换工具是fastjson,网上查知fastjson 有ValueFilter接口可以实现自定义过滤
packagecom.alibaba.fastjson.serializer; publicinterfaceValueFilterextendsSerializeFilter{ Objectprocess(Objectobject,Stringname,Objectvalue); }
知道接口后就简单了。
process(Objectobject,Objectvalue)//三个参数,object为要转成json的对象,name是对象的get/is方法的名字(去掉get或is前缀并首字母小写),value就是对应的get值 //思路就是通过object和name反射方法得出其return的类型。针对value==null的基础数据类型的或者list的类型的做出不同处理 //实现的部分代码(PS:时间类型我也算到基础类型了。) privatestaticString[]types={"java.lang.Integer","java.lang.Double","java.lang.Float","java.lang.Long","java.lang.Short","java.lang.Byte","java.lang.Boolean","java.lang.Char","java.lang.String","java.util.Date","int","double","long","short","byte","boolean","char","float"}; privatestaticStringfirst2Up(Stringstr){ returnstr.substring(0,1).toUpperCase()+str.substring(1); } privatestaticValueFilternullValueFilter=newValueFilter(){ @Override publicObjectprocess(Objectobject,Objectvalue){ if(value==null){ try{ Methodmethod=object.getClass().getDeclaredMethod("get"+first2Up(name)); for(Stringtype:types){ if(method.getReturnType().getName().equals(type)){ return""; } } if(method.getReturnType().isAssignableFrom(List.class)&& !method.getReturnType().getName().equals("java.lang.Object")){ returnnewint[0]; } returnnewObject(); }catch(SecurityException|NoSuchMethodExceptione){ e.printStackTrace(); returnvalue; } } returnvalue; } }; privatestaticStringdateFormat="yyyy-MM-ddHH:mm:ss"; privatestaticSerializeConfigmapping=newSerializeConfig(); static{ mapping.put(Date.class,newSimpleDateFormatSerializer(dateFormat)); } //只是部分代码,有些数字类型,也需要加上引号过滤的对象是notNullValueFilter,原理一样,就不贴出来了,mapping是对日期的格式化方法 publicstaticStringtoJsonString(Objectobj){ SerializeFilter[]filters={nullValueFilter,notNullValueFilter}; returnJSON.toJSONString(obj,mapping,filters); }
附上原先的json接口转换方法,希望能抛砖引玉
publicStringobject2Json(Objectobject)throwsIOException{ if(!objectUtil.isNotEmpty(object)){ return""; } ObjectMappermapper=JacksonMapper.getInstance(); //字段和值都加引号 mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES,true); //数字加引号 mapper.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS,true); mapper.configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS,true); mapper.getSerializerProvider().setNullValueSerializer(newJsonSerializer<Object>() { publicvoidserialize( Objectvalue,JsonGeneratorjg,SerializerProvidersp)throwsIOException,JsonProcessingException { jg.writeString(""); } }); returnmapper.writeValueAsString(object); }