fastjson 在 toJSONString 输出时 @Transient 注解必须有对应的属性定义才会起效

kmbjn2e3  于 2022-12-31  发布在  其他
关注(0)|答案(1)|浏览(149)

在调用 toJSONString 将 Java Bean 转化为 JSON 格式字符串时,使用 @transient 定义的 get 或 is 方法,必须要有对应的属性定义,才不会输出相应的字段。见如下示例:

public static class Bean {
    private String id;
    private String name;
    //private boolean succeed;
    
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
    
    @Transient
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    @Transient
    public boolean isSucceed() {
        return id != null && name != null;
    }
}

@Test
public void test1() {
    JSON.DEFAULT_GENERATE_FEATURE = SerializerFeature.config(JSON.DEFAULT_GENERATE_FEATURE, SerializerFeature.SkipTransientField, true);
    
    Bean bean = new Bean();
    bean.setId("100");
    bean.setName("CNJ");
    System.out.println(JSON.toJSONString(bean));
}

输出结果

{"id":"100","succeed":true}

期待结果

{"id":"100"}

mfuanj7w

mfuanj7w1#

17年就提出来的issue,到现在还不解决吗

相关问题