objectmapper用法
时间: 2023-05-27 17:07:00 浏览: 240
mapper 教程
ObjectMapper是一个Java库,用于将JSON数据转换为Java对象或将Java对象转换为JSON数据。它提供了一种简单易用的方式来处理JSON数据,使得在Java应用程序中使用JSON数据变得更加方便。以下是ObjectMapper用法的一些示例:
1. 将JSON字符串转换为Java对象:
```
ObjectMapper objectMapper = new ObjectMapper();
String json = "{\"name\":\"John\", \"age\":30}";
Person person = objectMapper.readValue(json, Person.class);
```
2. 将Java对象转换为JSON字符串:
```
ObjectMapper objectMapper = new ObjectMapper();
Person person = new Person("John", 30);
String json = objectMapper.writeValueAsString(person);
```
3. 将JSON字符串转换为Java集合:
```
ObjectMapper objectMapper = new ObjectMapper();
String json = "[{\"name\":\"John\", \"age\":30}, {\"name\":\"Jane\", \"age\":25}]";
List<Person> persons = objectMapper.readValue(json, new TypeReference<List<Person>>(){});
```
4. 将Java集合转换为JSON字符串:
```
ObjectMapper objectMapper = new ObjectMapper();
List<Person> persons = Arrays.asList(new Person("John", 30), new Person("Jane", 25));
String json = objectMapper.writeValueAsString(persons);
```
5. 使用ObjectMapper配置:
```
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 禁止序列化null值
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
```
阅读全文