首页 > 解决方案 > ObjectMapper 向 JSON 字符串添加额外的字段

问题描述

我有以下问题。

这是我的Accident班级和CommonDomainEntity班级:

@NoArgsConstructor
@AllArgsConstructor
@Data
public class Accident extends CommonDomainObject {
    private String status;
    private Date accidentDate;
    private String name;
}

@Data
public abstract class CommonDomainObject {
    public Long id;

    public boolean isNew() {
        return null == getId();
    }
}

在我的测试课中,我调用以下内容:

String exp = objMapper.writeValueAsString(accidents);
System.out.println(exp);
ResponseEntity<String> res = restTemplate.getForEntity("/accidents", String.class);

assertEquals(HttpStatus.OK, res.getStatusCode());
JSONAssert.assertEquals(exp, res.getBody(), false);

它抛出以下错误:

java.lang.AssertionError: [id=2]
Expected: new
but none found
; [id=3]
Expected: new
but none found

我已经尝试打印出对象exp以查看其中的内容,以及尝试打印出什么s in意外。

正如您在控制台日志中看到的那样,由于某种原因exp对象中有一个new=false字段,我无法弄清楚这是从哪里来的。

这就是我的事故清单中的内容

Accident(status=pending, accidentDate=null, name=Name), 
Accident(status=closed, accidentDate=null, name=Name)]

这是我exp的 JSON 对象

[{"id":2,"status":"pending","accidentDate":null,"name":"Name","new":false}, 
{"id":3,"status":"closed","accidentDate":null,"name":"Name","new":false}]

标签: javajsonspring-bootjackson

解决方案


CommonDomainObject.isNew()在抽象类中的方法被评估为 JSON 字段ObjectMapper。您必须使用杰克逊注释排除它。

public abstract class CommonDomainObject {
    ...
    @JsonIgnore
    public boolean isNew() {
        return null == getId();
    }
}

看:

您的MCVE将是:

  1. 称呼objMapper.writeValueAsString()
  2. 检查生成的 JSON 字符串表示为什么包含该new字段

所有其他代码对于重现您的问题都是多余的:)


推荐阅读