要将 JSON 字符串转换成 List,您可以使用 Jackson 库的 ObjectMapper 类来实现。

首先,您需要创建一个 ObjectMapper 对象,然后使用其 readValue() 方法将 JSON 字符串转换为 List 对象。以下是一个示例代码:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    public static void main(String[] args) {
        String json = '[{"name":"John","age":30},{"name":"Jane","age":25}]';

        ObjectMapper objectMapper = new ObjectMapper();

        try {
            List<UserDTO> userList = objectMapper.readValue(json, new TypeReference<List<UserDTO>>() {});
            System.out.println(userList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在上面的示例中,我们首先定义了一个 JSON 字符串,然后创建了一个 ObjectMapper 对象。接下来,我们使用 readValue() 方法将 JSON 字符串转换为 List 对象。注意,我们使用 TypeReference 类来指定转换的目标类型。

最后,我们将转换后的 List 对象打印出来。

确保在项目中包含 Jackson 库的依赖,以便使用 ObjectMapper 类。在 Maven 项目中,您可以将以下依赖添加到 pom.xml 文件中:

<dependencies>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.12.4</version>
    </dependency>
</dependencies>

这样,您就可以成功将 JSON 字符串转换成 List 对象了。

Jackson: 将 JSON 字符串转换为 List<UserDTO>

原文地址: https://www.cveoy.top/t/topic/fFDt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录