Returning JSON
Returning JSON means answering a request with JSON data. JSON is text with named fields that programs can read.
A record for the answer
This record holds a name and an age.
public record Person(String name, int age) {}Return the record
This method returns a person named Ana, aged 30.
public Person person() {
return new Person("Ana", 30);
}The JSON answer
This command asks the app for the answer at /person.
curl http://localhost:8080/personExample
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PersonController {
public record Person(String name, int age) {
}
@GetMapping("/person")
public Person person() {
return new Person("Ana", 30);
}
}Key points
- A controller method can return an object, not just text.
- Spring turns the object into JSON before it answers.
- JSON is text with named fields that programs can read.
- A record holds the fields for one answer.
- The record fields become the JSON fields.
- The field order in JSON follows the record order.
In this example, the annotation marks PersonController as a controller. The record Person holds a name and an age. The @GetMapping line ties the method to the address /person. The method returns a person named Ana, aged 30. Spring turns the record into JSON, and the answer holds the name and the age.
Note
The browser gets JSON text, not the Java object.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does Spring return when a method returns a record?