本指南探讨了如何在Spring Boot应用程序中使用ObjectMapper将Java对象转换为JSON,以及将JSON转换回Java对象。它涵盖了关键用例,例如自定义JSON字段名称、处理未知属性、处理列表,以及为特殊场景(如日期格式和美化打印)配置ObjectMapper。
ObjectMapper是Spring Boot中的一个关键组件,用于将Java对象序列化为JSON,并将JSON反序列化为Java对象。
以下是一些常见的ObjectMapper用例及代码示例:
1. 基本对象到JSON的转换
此用例涉及将Java对象转换为JSON。
import com.fasterxml.jackson.databind.ObjectMapper;public class ObjectToJsonExample {public static void main(String[] args) throws Exception {ObjectMapper objectMapper = new ObjectMapper();Employee employee = new Employee(1, "John", "Developer");// 将对象转换为JSONString jsonString = objectMapper.writeValueAsString(employee);System.out.println(jsonString);}
}
2. 基本JSON到对象的转换
此用例演示了将JSON字符串反序列化为Java对象。
import com.fasterxml.jackson.databind.ObjectMapper;public class JsonToObjectExample {public static void main(String[] args) throws Exception {String jsonString = "{\"id\":1,\"name\":\"John\",\"designation\":\"Developer\"}";ObjectMapper objectMapper = new ObjectMapper();// 将JSON字符串转换为Java对象Employee employee = objectMapper.readValue(jsonString, Employee.class);System.out.println(employee.getName()); // 输出: John}
}
3. 使用注解自定义JSON字段名称
在某些情况下,Java对象中的字段名称可能与JSON中的字段名称不匹配。使用@JsonProperty来处理此问题。
import com.fasterxml.jackson.annotation.JsonProperty;public class Employee {private int id;@JsonProperty("full_name")private String name;private String designation;// 构造函数、getter、setter
}
JSON
:
{"id": 1,"full_name": "John","designation": "Developer"
}
4. 序列化时忽略字段
在将对象转换为JSON时,可能需要忽略某些字段。使用@JsonIgnore来跳过这些字段。
import com.fasterxml.jackson.annotation.JsonIgnore;public class Employee {private int id;private String name;@JsonIgnoreprivate String password; // 序列化时将忽略此字段// 构造函数、getter、setter
}
5. 处理未知的JSON字段
在反序列化时,JSON中可能存在Java对象中不存在的字段。使用@JsonIgnoreProperties(ignoreUnknown = true)来避免因未知字段而导致的错误。
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;@JsonIgnoreProperties(ignoreUnknown = true)
public class Employee {private int id;private String name;private String designation;// 构造函数、getter、setter
}
6. 将对象列表转换为JSON
您可以使用ObjectMapper轻松地序列化和反序列化对象列表。
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;import java.util.Arrays;
import java.util.List;public class ListToJsonExample {public static void main(String[] args) throws Exception {ObjectMapper objectMapper = new ObjectMapper();List<Employee> employees = Arrays.asList(new Employee(1, "John", "Developer"),new Employee(2, "Jane", "Tester"));// 将列表转换为JSONString jsonString = objectMapper.writeValueAsString(employees);System.out.println(jsonString);// 将JSON转换回列表List<Employee> employeeList = objectMapper.readValue(jsonString, new TypeReference<List<Employee>>() {});System.out.println(employeeList.get(0).getName()); // 输出: John}
}
7. 在Spring Boot控制器中使用ObjectMapper
在Spring Boot中,ObjectMapper可以用于REST API中处理JSON输入和输出。
@RestController
@RequestMapping("/employees")
public class EmployeeController {@Autowiredprivate ObjectMapper objectMapper;@PostMapping("/create")public String createEmployee(@RequestBody String employeeJson) throws Exception {Employee employee = objectMapper.readValue(employeeJson, Employee.class);return "Employee created: " + employee.getName();}@GetMapping("/get")public String getEmployee() throws Exception {Employee employee = new Employee(1, "John", "Developer");return objectMapper.writeValueAsString(employee);}
}
8. 将JSON文件转换为对象
您可以直接将JSON文件反序列化为Java对象。
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;public class JsonFileToObjectExample {public static void main(String[] args) throws Exception {ObjectMapper objectMapper = new ObjectMapper();// 从文件中读取JSON并转换为Employee对象Employee employee = objectMapper.readValue(new File("employee.json"), Employee.class);System.out.println(employee.getName());}
}
9. 美化打印JSON输出
使用writerWithDefaultPrettyPrinter()来美化打印JSON输出,以提高可读性。
public class PrettyPrintJsonExample {public static void main(String[] args) throws Exception {ObjectMapper objectMapper = new ObjectMapper();Employee employee = new Employee(1, "John", "Developer");// 将对象转换为美化后的JSONString prettyJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);System.out.println(prettyJson);}
}
10. 自定义ObjectMapper配置
您可以根据特定需求配置ObjectMapper,例如处理空值、日期格式等。
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;public class CustomObjectMapperExample {public static void main(String[] args) throws Exception {ObjectMapper objectMapper = new ObjectMapper();// 注册Java 8时间模块以处理日期/时间objectMapper.registerModule(new JavaTimeModule());// 禁用日期的时间戳格式objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);// 转换带有LocalDate字段的Employee对象Employee employee = new Employee(1, "John", LocalDate.now());String jsonString = objectMapper.writeValueAsString(employee);System.out.println(jsonString);}
}
欢迎关注 SpringForAll社区(spring4all.com),专注分享关于Spring的一切!关注公众号:SpringForAll社区,回复“加群”还可加入Spring技术交流群!