fastjson在序列化时支持传入自定义的序列号过滤器,来定制序列化的结果
fastjson支持6种SerializeFilter,用于不同场景的定制序列化。
PropertyPreFilter 根据PropertyName判断是否序列化
PropertyFilter 根据PropertyName和PropertyValue来判断是否序列化
NameFilter 修改Key,如果需要修改Key,process返回值则可
ValueFilter 修改Value
BeforeFilter 序列化时在最前添加内容
AfterFilter 序列化时在最后添加内容
举个例子
public class Test { public static void main(String[] args) { HashMap<String, Object> map = new HashMap<>(); map.put("bizmonth","2020-12"); map.put("cust_total_num","0"); map.put("ventilation_total_num_1m","11"); HashMap<String, Object> map1 = new HashMap<>(); map1.put("bizmonth","2020-12"); map1.put("cust_total_num","0"); map1.put("ventilation_total_num_1m","11"); ArrayList<HashMap<String, Object>> mapList = Lists.newArrayList(map1, map); System.out.println(map); System.out.println("---------------"); String s = JSON.toJSONString(mapList, new ValueFilter() { @Override public Object process(Object o, String name, Object value) { if (name.equals("bizmonth")) { return "*****"; } return value; } }); System.out.println(s); } }
输出
[{"bizmonth":"*****","ventilation_total_num_1m":"11","cust_total_num":"0"},{"bizmonth":"*****","ventilation_total_num_1m":"11","cust_total_num":"0"}]
应用:对json中的日期进行格式化转换
public class DateTransform { public static String transform(String srcData, String srcFormat, String dstFormat) { DateFormatEnum from = DateFormatEnum.valueOf(srcFormat); DateFormatEnum to = DateFormatEnum.valueOf(dstFormat); TemporalAccessor parse = from.parse(srcData); return to.format(parse); } public static void main(String[] args) { HashMap<String, Object> map = new HashMap<>(); map.put("bizmonth", "2020-12"); map.put("cust_total_num", "0"); map.put("ventilation_total_num_1m", "11"); HashMap<String, Object> map1 = new HashMap<>(); map1.put("bizmonth", "2020-12"); map1.put("cust_total_num", "0"); map1.put("ventilation_total_num_1m", "11"); ArrayList<HashMap<String, Object>> mapList = Lists.newArrayList(map1, map); System.out.println(map); System.out.println("---------------"); String s = JSON.toJSONString(mapList, new ValueFilter() { @Override public Object process(Object o, String name, Object value) { if (name.equals("bizmonth")) { return transform((String) value, "YM", "YM2"); } return value; } }); System.out.println(s); } }