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); } }