Sending Pure JSON Objects to Views in Spring Boot
Spring Boot is a popular framework for building RESTful web applications. While it excels at working with data through REST APIs, you might also need to send JSON data directly to your view templates for dynamic rendering. This article explains how to send a pure JSON object (nested within a model object) from your Spring Boot controller to your view.
The Challenge: Pure JSON in View Templates
Imagine you have a Spring Boot controller that retrieves data from an external API. This data comes in JSON format, and you want to display it directly on your view using Thymeleaf, a popular templating engine for Spring Boot. The direct approach, using @ResponseBody
and @RestController
, won't work because these annotations are designed to handle REST API responses.
Example Scenario: Product Data from an API
Let's say you have a Product
model object and a controller method that fetches product data from an external API. Here's how you might structure your code:
Product Model:
public class Product {
private String id;
private String name;
private double price;
// Getters and Setters
}
Controller Method:
@GetMapping("/products")
public String getProducts(Model model) {
// Fetch product data from API as JSON
String apiResponse = fetchProductsFromAPI();
model.addAttribute("products", apiResponse); // Incorrect!
return "products"; // Thymeleaf template
}
This code will try to send the raw JSON string to the view, which will result in an error. Thymeleaf expects a Java object or a list of objects to render.
The Solution: Serialization and JSON Parsing
The key to successfully sending pure JSON data to your view is to serialize the JSON string into a Java object, allowing Thymeleaf to process and render it correctly.
-
Deserialize JSON to Java Object: Use a JSON library like Jackson or Gson to deserialize the JSON response into a Java object.
-
Add to Model: Add the deserialized Java object to the model using
model.addAttribute()
. -
Render in Thymeleaf: In your Thymeleaf template, you can then access the data from the deserialized Java object.
Example with Jackson
@GetMapping("/products")
public String getProducts(Model model) throws JsonProcessingException {
// Fetch product data from API as JSON
String apiResponse = fetchProductsFromAPI();
// Deserialize JSON to Product object (assuming API returns a list of Products)
ObjectMapper mapper = new ObjectMapper();
List<Product> products = mapper.readValue(apiResponse, new TypeReference<List<Product>>() {});
// Add Product list to model
model.addAttribute("products", products);
return "products";
}
Thymeleaf template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Products</title>
</head>
<body>
<h1>Products</h1>
<ul>
<li th:each="product : ${products}">
<span th:text="${product.name}"></span> -
<span th:text="${product.price}"></span>
</li>
</ul>
</body>
</html>
Conclusion:
By correctly serializing the JSON string into a Java object, you can seamlessly send pure JSON data to your Spring Boot views for dynamic rendering. This approach provides a powerful method to leverage the versatility of JSON while retaining the ease of use and expressiveness offered by Thymeleaf.