Returning JSON Responses in a Micronaut Controller
Micronaut is a modern Java framework designed to build lightweight and fast microservices. One of its core features is seamless JSON handling, making it easy to return JSON responses in RESTful applications. This article demonstrates how to return JSON responses from a Micronaut controller. We will cover returning a single JSON object, returning a list of JSON objects, and writing unit tests for the controller.
1. Setting Up the Micronaut Project
Before writing the controller, we need to set up a Micronaut project using Maven. You can create a Micronaut project using the Micronaut CLI:
1 | mn create-app com.jcg.micronaut-json --build=maven --lang=java |
Alternatively, you can use the Micronaut Launch tool to generate a Maven-based project.
2. Create a Data Model
In this article, we’ll use a Product
class to model product details. The Product
class below represents a simple model that we will use to return JSON responses in our Micronaut controller. Micronaut provides the @Serdeable
annotation to indicate that a class should be automatically serialized and deserialized.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 | @Serdeable public class Product { private String name; private double price; public Product(String name, double price) { this .name = name; this .price = price; } public String getName() { return name; } public double getPrice() { return price; } } |
2.1 What Does @Serdeable
Do?
@Serdeable
is part of Micronaut’s serialization mechanism. It marks a class as serializable and deserializable without requiring additional dependencies like Jackson or Gson. Micronaut generates compile-time serializers and deserializers for the class when this annotation is present.
Using @Serdeable
instead of @JsonProperty
(used in Jackson) is recommended for better integration with Micronaut’s lightweight serialization system. It allows Micronaut to efficiently convert objects to and from JSON while reducing startup time and memory usage.
3. Returning a Single JSON Object
Micronaut automatically serializes Java objects into JSON when returning them from a controller. The following example demonstrates how to return a single Product
JSON object.
1 2 3 4 5 6 7 8 9 | @Controller ( "/product" ) public class ProductController { @Get @Produces (MediaType.APPLICATION_JSON) public Product getProduct() { return new Product( "Laptop" , 1200.00 ); } } |
The @Controller("/product")
annotation maps this class to the /product
endpoint, while the @Get
annotation defines an HTTP GET request handler. The @Produces(MediaType.APPLICATION_JSON)
ensures that the response is returned as JSON. The getProduct()
method returns a Product
instance, which Micronaut automatically serializes into JSON.
Running the Application
Start the application:
1 | mvn mn:run |
Execute the following curl
command to test the endpoint:
1 | curl -X GET http: //localhost :8080 /product |
Expected Output:
1 2 3 4 | { "name" : "Laptop" , "price" : 1200.00 } |
4. Returning a List of JSON Objects
In most applications, we need to return a collection of objects. The following example demonstrates how to return a list of Product
objects.
01 02 03 04 05 06 07 08 09 10 11 12 | @Controller ( "/products" ) public class ProductListController { @Get @Produces (MediaType.APPLICATION_JSON) public List<Product> getProducts() { return Arrays.asList( new Product( "Laptop" , 1200.00 ), new Product( "Smartphone" , 800.00 ) ); } } |
In this code snippet, the getProducts()
method returns a list of Product
objects, which Micronaut automatically serializes into a JSON array.
Run the following curl
command to test the endpoint:
1 | curl -X GET http: //localhost :8080 /products |
Expected Output:
01 02 03 04 05 06 07 08 09 10 | [ { "name" : "Laptop" , "price" : 1200.00 }, { "name" : "Smartphone" , "price" : 800.00 } ] |
5. Testing the Micronaut Controller
Unit tests validate that our API works as expected. Micronaut provides built-in support for testing.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | @MicronautTest class ProductControllerTest { @Inject @Client ( "/" ) HttpClient client; @Test void testGetProduct() { HttpRequest<String> request = HttpRequest.GET( "/product" ); HttpResponse<Product> response = client.toBlocking().exchange(request, Product. class ); assertEquals( 200 , response.getStatus().getCode()); assertNotNull(response.body()); assertEquals( "Laptop" , response.body().getName()); assertEquals( 1200.00 , response.body().getPrice()); } @Test void testGetAllProducts() { HttpRequest<String> request = HttpRequest.GET( "/products" ); HttpResponse<List<Product>> response = client.toBlocking().exchange(request, Argument.listOf(Product. class )); assertEquals( 200 , response.getStatus().getCode()); assertNotNull(response.body()); assertEquals( 2 , response.body().size()); assertEquals( "Laptop" , response.body().get( 0 ).getName()); assertEquals( 1200.00 , response.body().get( 0 ).getPrice()); assertEquals( "Smartphone" , response.body().get( 1 ).getName()); assertEquals( 800.00 , response.body().get( 1 ).getPrice()); } } |
The testGetProduct()
method verifies that a single Product
is returned correctly by checking the response status and JSON fields, while the testGetAllProducts()
method ensures that the /products
endpoint returns a list of Product
objects, validating the response size and values. The use of Argument.listOf(Product.class)
ensures proper deserialization of the JSON array into a list of Product
objects, and assertions confirm the correctness of response status codes and field values.
Run mvn test
, and if successful, all tests will pass.
6. Conclusion
In this article, we explored how to return JSON responses in a Micronaut controller using a Product
entity. We covered setting up a Micronaut project with Maven, defining the Product
class with @Serdeable
for efficient serialization, and implementing controller methods to return both single and multiple JSON objects. Additionally, we demonstrated how to write unit tests to verify the API responses using Micronaut’s HTTP client.
7. Download the Source Code
You can download the full source code of this example here: return json in a micronaut controller