🎓 A1Learner
🔍
0 of 50 lessons completed

Leaving Fields Out of JSON

@JsonIgnore is an annotation that leaves a field out of JSON. An annotation is a marker that adds meaning to code.

Mark a field to skip

The note field carries the marker. Jackson will leave it out.

import com.fasterxml.jackson.annotation.JsonIgnore;

record Task(String title, boolean done, @JsonIgnore String note) {
}

The answer leaves the note out

The route returns three tasks with notes. The answer shows no notes.

@GetMapping("/tasks")
public List<Task> tasks() {
    return List.of(new Task("Buy milk", false, "aisle 4"), new Task("Ship Spring Boot", true, "release day"), new Task("Read a book", false, "chapter 2"));
}

Example

import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TaskController {

    record Task(String title, boolean done, @JsonIgnore String note) {
    }

    @GetMapping("/tasks")
    public List<Task> tasks() {
        return List.of(new Task("Buy milk", false, "aisle 4"), new Task("Ship Spring Boot", true, "release day"), new Task("Read a book", false, "chapter 2"));
    }
}

Key points

  • @JsonIgnore marks a field that JSON must skip.
  • Jackson reads the marker and leaves the field out.
  • The field still exists in the Java object.
  • Use it for a field that the answer should not show.
  • The other fields still appear in the answer.

In this example, the import brings in @JsonIgnore. The Task record holds a title, a done flag, and a note. The note carries the @JsonIgnore marker. The route answers GET /tasks with three tasks. Jackson turns the list into a JSON array. The array shows the title and the done flag only.

Note

@JsonIgnore hides the field from JSON only, not from Java code.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does @JsonIgnore do?