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

标签 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;

这在 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

您还可以通过注释字段声明或其 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/

相关文章:

java - 我们如何模拟 Ctrl+C 来阻止控制台应用程序等待 java 中的用户输入

java - ClassPathXmlApplicationContext : Error creating bean with name 'X' ; nested exception is java. lang.NoSuchMethodError : javax. persistence.Table.indexes()

java - 为什么我的Dojo.xhrGet调用错误Call Back方法

java - JSON 字符串到对象列表

java - 使用 Jackson 对不同请求的单个实体的不同属性进行 JSON 序列化

java - Spring @PropertySource 值不覆盖

java - 如何在java中的1个随机访问文件上有2个dataInputstream

java - Swagger Dropwizard 0.7 - 不显示 JSON 参数的 TextArea

java - 在 Spring-Boot 中为 soap webservice 抛出自定义异常?

java - 无法从 String 值反序列化 Spring-Boot Restful 项目