Jackson: 将 JSON 字符串转换为 List<UserDTO>
要将 JSON 字符串转换成 List
首先,您需要创建一个 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
最后,我们将转换后的 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
原文地址: https://www.cveoy.top/t/topic/fFDt 著作权归作者所有。请勿转载和采集!