使用 MapStruct 实现递归结构的序列化

使用 MapStruct 实现递归结构的序列化

本文档介绍了如何使用 mapStruct 库来序列化具有递归结构的 Java 对象,例如树形结构。通过定义多个 Mapper 接口,并结合 @Mapping 注解,可以优雅地将包含嵌套列表的实体类转换为对应的响应类,从而简化 API 响应的构建过程。

递归结构序列化方案

在开发 Java Web 应用程序时,经常需要将内部数据模型转换为外部 API 响应格式。对于具有递归结构的数据模型,例如树形结构,手动编写序列化逻辑会变得非常繁琐。MapStruct 是一个代码生成器,可以简化不同类型之间的映射。本文将介绍如何使用 MapStruct 来序列化包含递归结构的 Java 对象。

实体类与响应类定义

首先,定义需要映射的实体类和对应的响应类。以树形结构为例,包含 Tree 和 Leaf 两个实体类,以及对应的 TreeResponse 和 LeafResponse 响应类。

import lombok.*; import lombok.experimental.FieldDefaults;  import java.util.List;  import static lombok.AccessLevel.PUBLIC;  @Builder @Getter @AllArgsConstructor @FieldDefaults(level = PUBLIC) public class Tree {     String name;     List<Leaf> leafs; }
import lombok.*; import lombok.experimental.FieldDefaults;  import java.util.List;  import static lombok.AccessLevel.PUBLIC;  @Builder @Getter @AllArgsConstructor @FieldDefaults(level = PUBLIC) public class Leaf {     String name;     List<Leaf> children; }
import lombok.*; import lombok.experimental.FieldDefaults;  import java.util.List;  import static lombok.AccessLevel.PUBLIC;  @Getter @Setter @FieldDefaults(level = PUBLIC) public class TreeResponse {     String name;     List<LeafResponse> leafs; }
import lombok.*; import lombok.experimental.FieldDefaults;  import java.util.List;  import static lombok.AccessLevel.PUBLIC;  @Getter @Setter @FieldDefaults(level = PUBLIC) public class LeafResponse {     String name;     List<LeafResponse> children; }

定义 MapStruct Mapper 接口

为了实现 Tree 到 TreeResponse 以及 Leaf 到 LeafResponse 的映射,需要定义两个 MapStruct Mapper 接口。关键在于,需要一个单独的 Mapper 接口来处理 Leaf 及其子节点的递归映射。

import org.mapstruct.Mapper; import org.mapstruct.Mapping;  @Mapper public interface TreeMapper {      @Mapping(target = "name", source = "entity.name")     TreeResponse map(Tree entity); }
import org.mapstruct.Mapper; import java.util.List;  @Mapper public interface LeafMapperSecond {     LeafResponse map(Leaf entity);      List<LeafResponse> map(List<Leaf> entity); }

需要注意的是,LeafMapperSecond 接口需要定义两个 map 方法,一个用于映射单个 Leaf 对象,另一个用于映射 Leaf 对象的列表。MapStruct 会自动处理列表的递归映射。

测试用例

为了验证映射是否正确,可以编写一个测试用例。该用例创建一个包含嵌套 Leaf 对象的 Tree 对象,然后使用 MapStruct 将其映射到 TreeResponse 对象,并验证映射结果。

import org.junit.jupiter.api.Test; import org.mapstruct.factory.Mappers;  import java.util.ArrayList; import java.util.Arrays; import java.util.List;  import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull;  public class MapstructTest {      private TreeMapper treeMapper = Mappers.getMapper(TreeMapper.class);      @Test     public void test() {         List<Leaf> leafs = new ArrayList<>();         leafs.add(Leaf.builder().name("Leaf 1").build());          leafs.add(                 Leaf.builder()                         .name("Leaf 2")                         .children(                                 Arrays.asList(                                         Leaf.builder()                                                 .name("Leaf Children 1")                                                 .children(                                                         Arrays.asList(                                                                 Leaf.builder()                                                                         .name("Leaf Children 1.1")                                                                         .build(),                                                                 Leaf.builder()                                                                         .name("Leaf Children 1.2")                                                                         .build()))                                                 .build(),                                         Leaf.builder().name("Leaf Children 2").build()))                         .build());          Tree tree = Tree.builder().name("tree name").leafs(leafs).build();          TreeResponse treeResponse = treeMapper.map(tree);          assertEquals(treeResponse.name, "tree name");         assertEquals(treeResponse.leafs.size(), 2);          LeafResponse leafWithChildren =                 treeResponse.leafs.stream()                         .filter(l -> l.name.equals("Leaf 2"))                         .findFirst()                         .orElse(null);         assertNotNull(leafWithChildren);         assertEquals(leafWithChildren.getChildren().size(), 2);          LeafResponse leafWithSubChildren =                 leafWithChildren.children.stream()                         .filter(l -> l.name.equals("Leaf Children 1"))                         .findFirst()                         .orElse(null);          assertNotNull(leafWithSubChildren);         assertEquals(leafWithChildren.getChildren().size(), 2);     } }

注意事项

  • 确保 MapStruct 的依赖已正确添加到项目中。
  • 使用 @Mapper 注解标记 Mapper 接口,MapStruct 将自动生成实现类。
  • 对于递归结构,需要定义单独的 Mapper 接口来处理嵌套对象的映射。
  • MapStruct 会自动处理列表的映射,无需手动编写循环代码。

总结

通过使用 MapStruct,可以轻松地实现具有递归结构的 Java 对象的序列化。通过定义多个 Mapper 接口,并结合 @Mapping 注解,可以优雅地将包含嵌套列表的实体类转换为对应的响应类,从而简化 API 响应的构建过程。这种方法不仅减少了手动编写的代码量,还提高了代码的可读性和可维护性。

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享