如何使用TypeReference将类型A的list转换成类型B的list

    技术2022-07-10  108

    如何使用TypeReference将类型A的list转换成类型B的list

    1. 引入Maven Dependency2. 转换代码示例

    在代码编写时经常涉及到将一种类型的list转换成另一种类型的list。可以使用fasterxml的ObjectMapper来实现。

    1. 引入Maven Dependency

    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.11.1</version> </dependency>

    2. 转换代码示例

    ObjectMapper objectMapper = new ObjectMapper(); List<RouteDefinition> routeDefinitions = (List<RouteDefinition>) routeService.queryByCnd(cnd); List<RouteDefinitionVO> routeDefinitionVOs = objectMapper.convertValue(routeDefinitions, new TypeReference<List<RouteDefinitionVO>>() {});
    Processed: 0.061, SQL: 9