ObjectMapper 简介
ObjectMapper 是 Jackson 库的核心类,用于 Java 对象与 JSON 数据之间的相互转换。它支持序列化(对象转 JSON)和反序列化(JSON 转对象),广泛应用于 REST API、数据存储和配置处理等场景。
基本依赖配置
在 Maven 项目中添加 Jackson 依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.0</version>
</dependency>
序列化(对象转 JSON)
将 Java 对象转换为 JSON 字符串:
ObjectMapper mapper = new ObjectMapper();
User user = new User("Alice", 25);
String json = mapper.writeValueAsString(user);
System.out.println(json); // 输出:{"name":"Alice","age":25}
package com.example.util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ReSultMapUtil {
public static void main(String[] args) throws JsonProcessingException {
Map resultmap =new HashMap();
Map map1=new HashMap();
map1.put("age",18);
map1.put("tel","18788909090");
map1.put("name","zhangsan");
Map map2=new HashMap();
map2.put("age",19);
map2.put("tel","18888909090");
map2.put("name","lisan");
List list=new ArrayList<>();
list.add(map1);
list.add(map2);
resultmap.put("list",list);
System.out.println( buildSuccessMesage(resultmap));
}
static String buildSuccessMesage(Map bodymap){
ObjectMapper objectMapper = new ObjectMapper();
Map resultmap =new HashMap();
Map headtmap =new HashMap();
String result="";
headtmap.put("result","success");
headtmap.put("msgcode","200");
resultmap.put("SYSHEAD",headtmap);
resultmap.put("BODY",bodymap);
try {
result= objectMapper.writeValueAsString(resultmap);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return result;
}
}
注意事项:
- 类字段需提供 getter 方法,否则字段可能被忽略。
- 使用
@JsonInclude(JsonInclude.Include.NON_NULL)
可忽略 null 值字段。
反序列化(JSON 转对象)
将 JSON 字符串转换为 Java 对象:
String json = "{\"name\":\"Bob\",\"age\":30}";
User user = mapper.readValue(json, User.class);
System.out.println(user.getName()); // 输出:Bob
常见注解:
@JsonProperty
:自定义 JSON 字段名。@JsonIgnore
:忽略字段序列化。
处理复杂结构
嵌套对象转换:
public class Order {
private User user;
private List<String> items;
}
String orderJson = "{\"user\":{\"name\":\"Alice\"},\"items\":[\"item1\"]}";
Order order = mapper.readValue(orderJson, Order.class);
集合类型处理:
List<User> users = mapper.readValue("[{\"name\":\"Alice\"}]",
new TypeReference<List<User>>() {});
高级配置
日期格式化:
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
美化输出:
String prettyJson = mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(user);
忽略未知字段:
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
异常处理
捕获转换过程中的异常:
try {
User user = mapper.readValue(invalidJson, User.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
性能优化
- 复用
ObjectMapper
实例(线程安全)。 - 使用
JsonFactory
处理流式 JSON(大文件场景)。
通过以上方法,可以高效利用 ObjectMapper 实现 Java 与 JSON 的灵活转换。