[Mis][FastJson] 使用中的一些坑 - Gukie/learning GitHub Wiki

some tips

  • orders: 定义序列化出来的结果的字段顺序
  • ignores, 与includes 同时存在,ignore将会被忽略,只显示include中的字段信息(可通过JSONField的serialize来弥补)
  • ignores 是会继承的. includes也会继承;
  • 如果定义了includes,序列化出来的数据,只会包含includes中的字段

示例


public class Test extends TestCase {
    public void test_for_issue() throws Exception {
//        String json = JSON.toJSONString(new Test());
//        assertEquals("{\"zzz\":true}", json);

        PersonBean object = new PersonBean();
        String personJson = JSON.toJSONString(object);
//        assertEquals("{\"name\":\"lokia\",\"sex\":\"F\",\"age\":20}", personJson);
//        assertEquals("{\"name\":\"lokia\",\"sex\":\"F\",\"age\":20,\"location\":\"L.A.\",\"carNumber\":\"浙A45677\"}", personJson);
        assertEquals("{\"name\":\"lokia\",\"sex\":\"F\",\"location\":\"L.A.\",\"carNumber\":\"浙A45677\"}", personJson);
    }

    @JSONType(ignores = {"xxx", "yyy"})
    public static class Test {

        public boolean isXxx() {
            return true;
        }

        public boolean getYyy() {
            return true;
        }

        public boolean getZzz() {
            return true;
        }
    }

    /**
     * 1. ignores, 与includes 同时存在,ignore将会被忽略,只显示include中的字段信息(可通过JSONField的serialize来弥补)
     * 2. ignores 是会继承的. includes如果定义了,序列化出来的数据,只会包含includes中的字段
     */
    //    @JSONType(ignores = {"sex","age"})
//    @JSONType(orders = {"name", "sex", "age"},ignores = {"sex"},includes = {"name", "sex", "age","location","carNumber"})
//    @JSONType(orders = {"name", "sex", "age"},includes = {"name", "sex", "age","location","carNumber"})
    @JSONType(orders = {"name", "sex", "age"},includes = {"location","carNumber"})
    private static class PersonBean extends ParentBean{
        public String getName() {
            return "lokia";
        }

        @JSONField(serialize = false)
        public Integer getAge() {
            return 20;
        }

        public String getSex() {
            return "F";
        }
    }
//    @JSONType(orders = {"location,carNumber"},ignores = {"location","carNumber"})
    @JSONType(orders = {"location","carNumber"},ignores = {"location"})
    private static class ParentBean{
        public String getLocation(){
            return "L.A.";
        }
        public String getCarNumber(){
            return "浙A45677";
        }
    }
}