如何用Mapstruct实现Java递归树形结构的序列化?
使用Mapstruct实现树形结构的递归转换
Mapstruct原生支持递归对象转换,针对你给出的Tree/Leaf与TreeResponse/LeafResponse树形结构,只需定义简单的映射接口即可完成全量转换,无需手动编写递归逻辑。
步骤1:确保依赖配置正确(Maven示例)
在pom.xml中添加Mapstruct及Lombok的注解处理器配置,保证编译时生成正确的映射实现类:
<dependencies> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct</artifactId> <version>1.5.5.Final</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>17</source> <!-- 匹配你的项目Java版本 --> <target>17</target> <annotationProcessorPaths> <path> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>1.5.5.Final</version> </path> <path> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.30</version> </path> <!-- 可选:解决Lombok与Mapstruct的注解顺序冲突 --> <path> <groupId>org.projectlombok</groupId> <artifactId>lombok-mapstruct-binding</artifactId> <version>0.2.0</version> </path> </annotationProcessorPaths> </configuration> </plugin> </plugins> </build>
步骤2:定义映射接口
创建TreeMapper接口,声明内部模型到响应模型的转换方法。Mapstruct会自动识别递归结构,处理Leaf的children列表转换:
import org.mapstruct.Mapper; import java.util.List; // 配置componentModel为"spring",让Spring管理Mapper实例,可通过@Autowired注入 @Mapper(componentModel = "spring") public interface TreeMapper { // 转换Tree到TreeResponse,自动处理leafs列表的批量转换 TreeResponse treeToTreeResponse(Tree tree); // 转换单个Leaf到LeafResponse,Mapstruct会递归调用此方法处理children列表 LeafResponse leafToLeafResponse(Leaf leaf); // 批量转换Leaf列表到LeafResponse列表,Mapstruct自动生成循环调用逻辑 List<LeafResponse> leafListToLeafResponseList(List<Leaf> leafs); }
步骤3:在业务代码中使用
在Spring环境下,直接注入TreeMapper即可完成转换:
@RestController @RequestMapping("/trees") public class TreeController { private final TreeMapper treeMapper; private final TreeService treeService; public TreeController(TreeMapper treeMapper, TreeService treeService) { this.treeMapper = treeMapper; this.treeService = treeService; } @GetMapping("/{id}") public TreeResponse getTree(@PathVariable Long id) { // 获取内部树形模型 Tree internalTree = treeService.getTreeById(id); // 转换为响应模型 return treeMapper.treeToTreeResponse(internalTree); } }
关键说明
- 递归自动处理:Mapstruct会检测到
Leaf.children是List<Leaf>,而LeafResponse.children是List<LeafResponse>,因此会自动递归调用leafToLeafResponse方法处理所有子节点,无需手动编写递归代码。 - 字段匹配:由于你的模型类字段名完全一致(如
name、children、leafs),Mapstruct会自动完成字段映射,无需额外配置@Mapping注解。如果字段名不一致,可通过@Mapping(target = "目标字段", source = "源字段")指定映射关系。 - Lombok配合:建议给所有模型类添加
@Data注解,自动生成getter/setter方法,Mapstruct依赖这些方法完成字段读取与赋值。
内容的提问来源于stack exchange,提问作者JaimeASV
相关产品推荐
相关产品推荐

