🎓 A1Learner
🔍
0 of 50 lessons completed

Field Names in JSON

A JSON field name is the key that names a value in JSON. @JsonProperty renames a field in the JSON.

Rename one field

This record renames title to task_title in the JSON. The done field keeps its name.

record TaskForm(@JsonProperty("task_title") String title, boolean done) {}

Return the renamed task

Ask for /task. The answer carries task_title instead of title.

@GetMapping("/task")
public TaskForm task() {
    return new TaskForm("Buy milk", false);
}

Example

package com.example.demo;

import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TaskController {

  record TaskForm(@JsonProperty("task_title") String title, boolean done) {
  }

  @GetMapping("/task")
  public TaskForm task() {
    return new TaskForm("Buy milk", false);
  }
}

Key points

  • @JsonProperty sits on a record part and renames its JSON field.
  • Jackson is the library that turns Java objects into JSON.
  • The new name appears in answers and in requests the route reads.
  • Parts without the annotation keep their own names.
  • Rename a field when the JSON must use a different name.

In this example, the record TaskForm holds a title and a done flag. The annotation @JsonProperty renames title to task_title in the JSON. The controller has one route. The route answers GET requests for /task. The method builds one task with the title Buy milk and done set to false. Spring Boot turns the record into JSON for the answer. The JSON carries task_title instead of title, and done keeps its name.

Note

The Java name stays the same, so code still uses title.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does @JsonProperty("task_title") do on String title?