fastjson2 icon indicating copy to clipboard operation
fastjson2 copied to clipboard

[BUG] 当 field 和 getter方法 均为 public 时,默认以 Field 优先输出

Open CodePlayer opened this issue 1 year ago • 2 comments

问题描述

@Getter
@Setter
public static class AccountVO {

    public long amount;

    public BigDecimal getAmount() {
        return BigDecimal.valueOf(amount).movePointLeft(2);
    }

}

@Test
public void test() throws Exception {
    AccountVO vo = new AccountVO();
    vo.setAmount(10000L);
    System.out.println(JSON.toJSONString(vo)); // {"amount":10000}
}

环境信息

  • OS信息: CentOS 8.x / Windows 11 64bit
  • JDK信息:Openjdk/Oracle JDK 17.0.11
  • 版本信息:Fastjson2 2.0.51

重现步骤

直接执行上述单元测试即可,稳定复现。

期待的正确结果

按照 JavaBean 的规范,似乎应该以 getter 方法 的返回值优先输出 ?

附加信息

这个修复改动可能会有向后兼容性的影响,请审慎评估。

这种写法可能不推荐,但在业务实现中具有现实意义。 比如, 我们想通过 total.amount += vo.amount 实现快速累加,而 getAmount() 用于对外输出。 如果不将 amount 字段保持 public,就需要 total.setAmount( total.getAmount().add( vo.getAmount() ).movePointRight(2) )

CodePlayer avatar Jul 02 '24 03:07 CodePlayer

试试禁止 amount 字段序列化?

  @Getter
  @Setter
  public static class AccountVO {

      @JSONField(serialize = false)
      public long amount;

      public BigDecimal getAmount() {
          return BigDecimal.valueOf(amount).movePointLeft(2);
      }
  }

输出{"amount":100.00}

jihuayu avatar Jul 03 '24 02:07 jihuayu

要优先field,要不然android下性能会变差

wenshao avatar Jul 07 '24 00:07 wenshao