1、指定序列化顺序
缺省fastjson序列化一个java bean,是根据fieldName的字母序进行序列化的,你可以通过ordinal指定字段的顺序。这个特性需要1.1.42以上版本。
1 public static class VO { 2 @JSONField(ordinal = 3) 3 private int f0; 4 5 @JSONField(ordinal = 2) 6 private int f1; 7 8 @JSONField(ordinal = 1) 9 private int f2; 10 }
2、fastjson 忽略字段:
1 public void test01(){ 2 List<User> list = new ArrayList<>(); 3 4 User user1 = new User("lisi", 14); 5 User user2 = new User("zs", 18); 6 7 list.add(user1); 8 list.add(user2); 9 10 System.out.println("未忽略字段前:"+JSONArray.toJSON(list));//未忽略前:[{"name":"lisi","age":14},{"name":"zs","age":18}] 11 12 SimplePropertyPreFilter filter = new SimplePropertyPreFilter(); 13 filter.getExcludes().add("age"); 14 System.out.println("忽略字段后:"+JSONObject.toJSONString(list, filter));//忽略后:[{"name":"lisi"},{"name":"zs"}] 15 }
3、fastjson 格式化日期:
1 public void test01() { 2 3 User lisi = new User("lisi", 13, new Date()); 4 System.out.println(lisi);//User{name='lisi', age=13, date=Fri Mar 30 22:00:48 CST 2018} 5 System.out.println(JSON.toJSONStringWithDateFormat(lisi, "yyyy-MM-dd HH:mm:ss.SSS")); 6 //{"age":13,"date":"2018-03-30 21:59:33.204","name":"lisi"} 7 8 }
4、抽取忽略字段形成工具:
1 /** 2 * @param list 3 * @param args 排除字段 4 * @return 5 */ 6 public static String list2Json(List list,String[] args){ 7 if (args != null && args.length>0){ 8 SimplePropertyPreFilter filter = new SimplePropertyPreFilter(); 9 for (String arg : args) { 10 filter.getExcludes().add(arg); 11 } 12 return JSONObject.toJSONString(list, filter); 13 } 14 return JSONObject.toJSONString(list); 15 }