ObjectMapper向JSON字符串添加额外的字段

时间:2019-06-05 08:42:14

标签: java json spring-boot jackson

我有以下问题。

这是我的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}]

2 个答案:

答案 0 :(得分:1)

在我看来,您正在将事故列表转换为字符串,并将其与来自也是字符串的restTemplate调用的响应进行比较。其余服务将返回不属于Accident对象的其他属性。解决方法是向事故对象添加额外的属性,以使服务响应与域模型保持一致

答案 1 :(得分:0)

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

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

请参阅:

您的MCVE为:

  1. 致电objMapper.writeValueAsString()
  2. 检查为什么生成的JSON字符串表示形式包含new字段

所有其他代码都可用于复制您的问题:)