ObjectMapper的常用方法 (对象和JSON数据之间的转换)

2023-12-23 23:37:42

<dependency>  
    <groupId>com.fasterxml.jackson.core</groupId>  
    <artifactId>jackson-databind</artifactId>  
    <version>2.13.0</version> <!-- 请根据实际情况选择合适的版本 -->  
</dependency>

ObjectMapper类是Jackson库中的主要类,用于在Java对象和JSON数据之间进行转换。以下是ObjectMapper的一些常用使用方法:

1. 将JSON字符串转换为Java对象:
String jsonString = "{\"name\":\"John\", \"age\":30}";  
ObjectMapper mapper = new ObjectMapper();  
MyClass obj = mapper.readValue(jsonString, MyClass.class);

2. 将Java对象转换为JSON字符串:
MyClass obj = new MyClass("John", 30);  
ObjectMapper mapper = new ObjectMapper();  
String jsonString = mapper.writeValueAsString(obj);

3. 将JSON数组转换为Java对象数组:
String jsonArrayString = "[{\"name\":\"John\", \"age\":30}, {\"name\":\"Jane\", \"age\":25}]";  
ObjectMapper mapper = new ObjectMapper();  
MyClass[] objArray = mapper.readValue(jsonArrayString, MyClass[].class);

4. 将Java对象数组转换为JSON数组:
MyClass[] objArray = new MyClass[]{new MyClass("John", 30), new MyClass("Jane", 25)};  
ObjectMapper mapper = new ObjectMapper();  
String jsonArrayString = mapper.writeValueAsString(objArray);

5. 将Java集合转换为JSON字符串:
List<MyClass> objList = new ArrayList<>(Arrays.asList(new MyClass("John", 30), new MyClass("Jane", 25)));  
ObjectMapper mapper = new ObjectMapper();  
String jsonArrayString = mapper.writeValueAsString(objList);

6. 将JSON字符串转换为Java Map:
String jsonMapString = "{\"name\":\"John\", \"age\":30}";  
ObjectMapper mapper = new ObjectMapper();  
Map<String, Object> map = mapper.readValue(jsonMapString, new TypeReference<Map<String, Object>>(){});

文章来源:https://blog.csdn.net/weixin_43652507/article/details/135175698
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。