我有以下 Java 类。
@Component
@JsonIgnoreProperties({"begin", "end"})
public class Event extends ResourceSupport {
@JsonProperty("name")
private final String name;
@JsonProperty("description")
private final String description;
@JsonProperty("timeZone")
private final ZoneId timeZone;
private final LocalDateTime begin;
private final LocalDateTime end;
这在 REST 服务中返回。无论我做什么,它总是返回 LocalDateTime
的深层对象表示,如下所示。
...
{"hour":1,"minute":0,"second":0,"nano":0},"midnightEndOfDay":false},{"month":"OCTOBER","timeDefinition":"UTC","standardOffset":{"totalSeconds":3600,"id":"+01:00","rules":{"fixedOffset":true,"transitions":[],"transitionRules":[]}},"offsetBefore":{"totalSeconds":7200,"id":"+02:00","rules":{"fixedOffset":true,"transitions":[],"transitionRules":[]}},"offsetAfter":{"totalSeconds":3600,"id":"+01:00
...
我也尝试过将 @JsonIgnore
直接放在它们上面。
下面是 Controller :
@RequestMapping("/api/hello")
@ResponseBody
HttpEntity<Event> getEvent() {
Event event = new Event("name", "description", ZoneId.of("Europe/Paris"),
LocalDateTime.now().plusDays(1), LocalDateTime.now().plusDays(2));
event.add(linkTo(methodOn(EventApi.class).getEvent()).withSelfRel());
return new ResponseEntity<Event>(event, HttpStatus.OK);
}
我也在试用 Spring HATEOAS,所以我不确定这是否与它有关。
鉴于 SpringBoot 固执己见的本性,我是否应该使用不同的开发模式?
最佳答案
要使 JsonIgnoreProperties
用于序列化,您必须指定要忽略的变量名称,例如
@JsonIgnoreProperties({"begin", "end", "timeZone"})
根据文档,这些是逻辑名称,例如有名为 getBegin()
和 getEnd()
您还可以通过注释字段声明或其 getter 来获取在序列化期间忽略的字段。 例如1
@JsonIgnore
private final LocalDateTime begin;
例如2
@JsonIgnore
public LocalDateTime getBegin() {
return begin;
}
由于字段名称是硬编码在@JsonIgnoreProperties 注释中的,因此在重命名字段时有可能出错。因此,@JsonIgnore 优于 @JsonIgnoreProperties。
关于java - 如何让@JsonIgnore 工作以便不递归返回 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32298722/