在Spring Boot中使用枚举创建父子JSON响应,可以通过定义枚举类和使用Jackson库的注解来实现。以下是一个详细的步骤和示例代码:
假设我们有一个表示组织结构的枚举,其中包含父级和子级的关系。
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
public enum OrganizationRole {
CEO("CEO"),
MANAGER("Manager", CEO),
DEVELOPER("Developer", MANAGER),
TESTER("Tester", MANAGER);
private final String name;
private final OrganizationRole parent;
OrganizationRole(String name) {
this.name = name;
this.parent = null;
}
OrganizationRole(String name, OrganizationRole parent) {
this.name = name;
this.parent = parent;
}
@JsonValue
public String getName() {
return name;
}
public OrganizationRole getParent() {
return parent;
}
@JsonCreator
public static OrganizationRole fromName(String name) {
for (OrganizationRole role : OrganizationRole.values()) {
if (role.getName().equalsIgnoreCase(name)) {
return role;
}
}
throw new IllegalArgumentException("Unknown role: " + name);
}
}
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class OrganizationController {
@GetMapping("/roles")
public OrganizationRole[] getRoles() {
return OrganizationRole.values();
}
}
确保在你的pom.xml
中包含Spring Boot和Jackson的依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
当你访问/roles
端点时,Spring Boot会自动将枚举数组序列化为JSON。由于我们使用了@JsonValue
注解,只有name
属性会被序列化到JSON中。
@JsonValue
注解。@JsonCreator
注解并正确实现了构造函数。通过这种方式,你可以灵活地在Spring Boot中使用枚举来创建复杂的父子JSON响应。
领取专属 10元无门槛券
手把手带您无忧上云