如何让 @JsonIgnore 工作,以便不递归返回 JSON?

Rob*_*ers 5 java jackson spring-boot

我有以下 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;
Run Code Online (Sandbox Code Playgroud)

这在 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
    ...
Run Code Online (Sandbox Code Playgroud)

我也试过@JsonIgnore直接放在它们上面。

下面是控制器:

@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);

    }
Run Code Online (Sandbox Code Playgroud)

我也在尝试 Spring HATEOAS,所以我不确定这是否与它有关。

由于 SpringBoot 的自以为是,我应该使用不同的开发模式吗?

Man*_*dis 6

JsonIgnoreProperties进行序列化,您必须指定要忽略的变量名称,例如

@JsonIgnoreProperties({"begin", "end", "timeZone"})
Run Code Online (Sandbox Code Playgroud)

根据文档,这些是逻辑名称,例如有命名的吸气剂getBegin()getEnd()

您还可以通过注释字段声明或其 getter 来获取在序列化期间被忽略的字段。例如1

@JsonIgnore
private final LocalDateTime begin;
Run Code Online (Sandbox Code Playgroud)

例2

@JsonIgnore
public LocalDateTime getBegin() {
    return begin;
}
Run Code Online (Sandbox Code Playgroud)

由于字段名称是在 @JsonIgnoreProperties 注释中硬编码的,因此在重命名字段时可能会出错。因此,@JsonIgnore 优于 @JsonIgnoreProperties。