【问题标题】:Jackson return multiple(duplicate) feilds杰克逊返回多个(重复)字段
【发布时间】:2020-02-23 13:33:55
【问题描述】:

JAVA POJO:

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;

@Getter @Setter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Test1 {
    @JsonProperty("aBCFeexxxx")
    private double aBCFee;

}

测试代码:

public static void main(String[] args) throws JsonProcessingException {
        Test1 t = new Test1();
        t.setABCFee(10l);       
        System.out.println((new ObjectMapper()).writeValueAsString(t));
    }

输出: {"abcfee":10.0,"aBCFeexxxx":10.0}

为什么在输出中返回acbfee? 期望我们只需要返回aBCFeexxxx

我做错了什么?

PS:

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.6</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.6</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.6</version>
        </dependency>

【问题讨论】:

  • 我无法复制该问题。这是我得到的输出:{"aBCFeexxxx":10.0}
  • 杰克逊版本是什么?
  • @michalk 更新版本问题... com.fasterxml.jackson.core:jackson-databind:2.9.6

标签: java json serialization jackson jackson2


【解决方案1】:

Lombok 和 Jackson 对名为 aBCFee 的属性的 getter 和 setter 的命名约定存在分歧。

我不使用 Lombok,所以我让 Eclipse 为我创建了 getter/setter,然后我得到了:

@JsonInclude(JsonInclude.Include.NON_NULL)
class Test1 {
    @JsonProperty("aBCFeexxxx")
    private double aBCFee;

    public double getaBCFee() {
        return this.aBCFee;
    }
    public void setaBCFee(double aBCFee) {
        this.aBCFee = aBCFee;
    }
}

如您所见,setter 方法被命名为setaBCFee,而不是setABCFee。此代码运行正常。

{"aBCFeexxxx":10.0}

当我随后重命名方法以匹配您所拥有的:

public double getABCFee() {
    return this.aBCFee;
}
public void setABCFee(double aBCFee) {
    this.aBCFee = aBCFee;
}

我得到了你得到的:

{"abcfee":10.0,"aBCFeexxxx":10.0}

如您所见,Jackson 将前 4 个字符小写,而不仅仅是第一个,因此就 Jackson 而言,getter/setter 定义的 abcfee 属性不同于 aBCFee 定义的属性字段,因此您会在 JSON 文本中获得两个属性。

Java 命名约定是将大写首字母缩略词小写,例如“大 HTML 文档”应命名为 bigHtmlDoc 作为字段,setBigHtmlDoc 作为设置器。我建议您将字段重命名为 abcFee

@JsonInclude(JsonInclude.Include.NON_NULL)
class Test1 {
    @JsonProperty("aBCFeexxxx")
    private double abcFee;

    public double getAbcFee() {
        return this.abcFee;
    }

    public void setAbcFee(double abcFee) {
        this.abcFee = abcFee;
    }
}

杰克逊对此很满意:

{"aBCFeexxxx":10.0}

我自己没有 Lombok,我假设它会将 getter/setter 方法命名为相同,因此不再有任何差异。

【讨论】:

  • "大 HTML 文档" 很好的例子
猜你喜欢
  • 2013-08-16
  • 1970-01-01
  • 2015-03-20
  • 2021-04-02
  • 2012-02-25
  • 2020-06-30
  • 1970-01-01
  • 1970-01-01
  • 2016-09-11
相关资源
最近更新 更多