如何从Controller绑定JSON数据并在View中显示名称?附请求JSON示例
实现Controller绑定JSON数据并在View中展示名称
First, let's look at the formatted version of the JSON you captured for clarity:
[ { "id": "904c7ccd-d568-40ca-a3ab-1d097d555f52", "name": "BPANDE2", "actualName": "Pande, Bhavana (B.V.)", "displayName": "Pande, Bhavana (B.V.) (BPANDE2)", "email": "bpande2@abc.com", "deleted": false, "deletedDate": 0, "authenticationRealm": "f4191d4b-4331-4637-af6f-c89781687bf6", "isLockedOut": false, "lastLoginDate": 1521144701377, "isDeletable": true, "groups": [ { "id": "7862c275-8eb2-42cf-895c-214c2826a0b8", "name": "config_vi..." } ] } ]
I’ll assume you’re using Spring MVC (the most common framework for this scenario) — here’s a step-by-step breakdown to make this work:
1. Map JSON to Java Entity Classes
First, create POJO classes that mirror the JSON structure. This lets the framework automatically bind JSON data to usable objects.
Group.java (for the nested groups array)
public class Group { private String id; private String name; // Standard getters and setters public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
User.java (for the main user object)
import java.util.List; public class User { private String id; private String name; private String actualName; private String displayName; private String email; private boolean deleted; private long deletedDate; private String authenticationRealm; private boolean isLockedOut; private long lastLoginDate; private boolean isDeletable; private List<Group> groups; // Focused getters/setters for your display needs public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } // Add getters/setters for other fields as needed }
2. Controller: Fetch, Bind, and Pass Data to the View
In your Controller, retrieve the JSON (from an API, database, etc.), convert it to a list of User objects, and pass it to the View via the model.
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import java.util.List; @Controller public class UserController { @GetMapping("/user-names") public String loadUserNames(Model model) { // Replace this with your actual data source (e.g., REST API call, DB query) String rawJson = "[{\"id\":\"904c7ccd-d568-40ca-a3ab-1d097d555f52\",\"name\":\"BPANDE2\",\"actualName\":\"Pande, Bhavana (B.V.)\",\"displayName\":\"Pande, Bhavana (B.V.) (BPANDE2)\",\"email\":\"bpande2@abc.com\",\"deleted\":false,\"deletedDate\":0,\"authenticationRealm\":\"f4191d4b-4331-4637-af6f-c89781687bf6\",\"isLockedOut\":false,\"lastLoginDate\":1521144701377,\"isDeletable\":true,\"groups\":[{\"id\":\"7862c275-8eb2-42cf-895c-214c2826a0b8\",\"name\":\"config_vi...\"}]}]"; ObjectMapper objectMapper = new ObjectMapper(); List<User> userList = null; try { // Convert JSON string to a List<User> userList = objectMapper.readValue(rawJson, new TypeReference<List<User>>() {}); } catch (Exception e) { e.printStackTrace(); // In production, handle this properly (e.g., log error and redirect to an error page) } // Pass the user list to the View model.addAttribute("users", userList); return "user-display"; // Name of your View template file } }
3. View: Render the Names
Below are examples using two common View templates: Thymeleaf (Spring Boot’s default) and JSP.
Thymeleaf Template (user-display.html)
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>User Names</title> </head> <body> <h2>User Account Details</h2> <!-- Render users only if data exists --> <div th:if="${users != null and !users.isEmpty()}"> <ul> <!-- Loop through each user and display their names --> <li th:each="user : ${users}"> <strong>Login Name:</strong> <span th:text="${user.name}"></span><br> <strong>Display Name:</strong> <span th:text="${user.displayName}"></span> </li> </ul> </div> <!-- Fallback for empty data --> <div th:if="${users == null or users.isEmpty()}"> <p>No user data available.</p> </div> </body> </html>
JSP Template (user-display.jsp)
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>User Names</title> </head> <body> <h2>User Account Details</h2> <c:if test="${not empty users}"> <ul> <c:forEach var="user" items="${users}"> <li> <strong>Login Name:</strong> ${user.name}<br> <strong>Display Name:</strong> ${user.displayName} </li> </c:forEach> </ul> </c:if> <c:if test="${empty users}"> <p>No user data available.</p> </c:if> </body> </html>
Quick Pro Tips
- If JSON keys don’t match your Java field names, use
@JsonProperty("json-key-name")on the Java field to map them explicitly. - Always handle JSON parsing exceptions in production (don’t just print stack traces).
- Add null checks in the View to avoid runtime errors if data is missing.
内容的提问来源于stack exchange,提问作者Guru
相关产品推荐
相关产品推荐

