java - 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}]
解决方案
您CommonDomainObject.isNew()
在抽象类中的方法被评估为 JSON 字段ObjectMapper
。您必须使用杰克逊注释排除它。
public abstract class CommonDomainObject {
...
@JsonIgnore
public boolean isNew() {
return null == getId();
}
}
看:
- 想要隐藏由 Jackson 映射到 JSON 的对象的某些字段
- https://github.com/FasterXML/jackson-annotations/wiki/Jackson-Annotations
- https://github.com/FasterXML/jackson-annotations
您的MCVE将是:
- 称呼
objMapper.writeValueAsString()
- 检查生成的 JSON 字符串表示为什么包含该
new
字段
所有其他代码对于重现您的问题都是多余的:)
推荐阅读
- ios - 没有匹配的证书
- arrays - 如何检查字典数组中是否存在键值对?
- ios - Swift Realm 迁移创建从旧类型到新类型的引用
- redux - 使用返回带有参数的函数的函数
- c# - C# Linq 日期时间到字符串“dd/mm/yyyy”
- jquery - 删除动态创建的节点
- html - 根据屏幕尺寸有条件地显示 RenderBody
- ethereum - 与已部署的 Ethereum/Quorum 合约交互
- sql-server - Windows Server 2008 R2 和 Windows Server 2019 上的 Access 之间的显着性能差异
- java - 根据内部日期列表对 JAVA 父列表进行排序