【问题标题】:@JsonIgnore does not ignore fields in hibernate Entity@JsonIgnore 不会忽略休眠实体中的字段
【发布时间】:2018-12-31 00:43:22
【问题描述】:

我有一个具有 Id 属性的实体“任务”,但我不需要在 JSON 文件中返回该字段。

@Entity
public class Task {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonIgnore
    private Integer Id;
    @JsonProperty("task")
    private String taskName;

    private String status;
    //getter and setter
}

但是,当我发出 get 请求时,注解 @JsonIgnore 并没有过滤该字段,见下文:

{
    "status": "started",
    "timestamps": {
        "submitted": "2018-12-31T00:34:20.718+0000",
        "started": "2018-12-31T00:34:20.718+0000",
        "completed": "2018-12-31T00:34:20.718+0000"
    },
    "id": 40001,
    "task": "q094hiu3o"
}

防止“Id”显示的正确方法是什么?

【问题讨论】:

  • 尝试在 getter 方法上添加它
  • @Deadpool 它已经拥有所有的 getter 和 setter。
  • 我的意思是在 Getter 方法上添加该注释并尝试它
  • 我还观察到大小写差异private Integer Id;"id": 40001,

标签: java json hibernate jackson


【解决方案1】:

所以这是jacksonhibernate issue 的问题,请尝试在课堂级别使用@jsonIgnoreProperties

@JsonIgnoreProperties(ignoreUnknown = true, 
                  value = {"id"})

【讨论】:

  • 很高兴知道这些方法可能存在错误,我通常使用@JsonIgnoreProperties 只是为了忽略未知
【解决方案2】:

您可以尝试仅在您的 getter 上添加 @JsonIgnore

    @JsonIgnore
    public Integer getId() {
        return id;
    }

如果您使用的 Jackson 版本可用,我建议在您的 id 字段中添加 @JsonProperty 注释:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@JsonProperty(access = Access.WRITE_ONLY)
private Integer id;

只写 访问设置,表示该属性只能在反序列化时被写入(设置),而在序列化时不会被读取(获取),即属性的值不包含在序列化中

Jackson documentation here

【讨论】:

  • 也许您将序列化与反序列化混淆了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-07
  • 2011-11-08
  • 1970-01-01
  • 2020-02-16
  • 2023-03-22
  • 2014-09-12
  • 2011-12-11
相关资源
最近更新 更多