Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get @JsonIgnore to work so that JSON are not returned recursively?

I have the following Java class.

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

this gets returned in a REST service. Regardless of what I do it always returns this deep object representation of LocalDateTime, like below.

    ...
{"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
    ...

I have also tried to put @JsonIgnore directly on them.

Below is the 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);

    }

I am also trying out Spring HATEOAS, so I'm not sure if that has something to do with it.

Is there a different development pattern I should be using, because of the opinionated nature of SpringBoot?

like image 743
Pompey Magnus Avatar asked Aug 30 '15 16:08

Pompey Magnus


1 Answers

For JsonIgnoreProperties to work for serialization you must specify the variable name(s) to ignore e.g.

@JsonIgnoreProperties({"begin", "end", "timeZone"})

According to documentation these are logical names e.g. there are getters named getBegin() and getEnd()

You can also get a field to be ignored during serialization by annotating the field declaration or its getter. e.g.1

@JsonIgnore
private final LocalDateTime begin;

e.g.2

@JsonIgnore
public LocalDateTime getBegin() {
    return begin;
}

Since the field names are hard-coded in @JsonIgnoreProperties annotation, there are chances of making mistakes while renaming the fields. For that reason, @JsonIgnore is preferred over @JsonIgnoreProperties.

like image 154
Manos Nikolaidis Avatar answered Oct 05 '22 11:10

Manos Nikolaidis