如何用ObjectMapper实现Java对象的简单映射示例?

2026-05-21 06:405阅读0评论SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计1137个文字,预计阅读时间需要5分钟。

如何用ObjectMapper实现Java对象的简单映射示例?

一、什么是ObjectMapper?

ObjectMapper是Jackson库的主要类,它提供了一些将数据集或对象转换的功能。它可以将数据集或对象转换为JSON格式,也可以将JSON字符串转换回数据集或对象。

二、ObjectMapper的使用方法

ObjectMapper的使用方法如下:

1. 创建ObjectMapper实例。

2.使用ObjectMapper的readValue方法将JSON字符串转换为对象。

3.使用ObjectMapper的writeValue方法将对象转换为JSON字符串。

示例代码:

java

import com.fasterxml.jackson.databind.ObjectMapper;

public class ObjectMapperExample { public static void main(String[] args) { try { // 创建ObjectMapper实例 ObjectMapper mapper=new ObjectMapper();

// 将JSON字符串转换为对象 String json={\name\:\John\, \age\:30}; Person person=mapper.readValue(json, Person.class);

// 将对象转换为JSON字符串 String jsonResult=mapper.writeValueAsString(person); System.out.println(jsonResult); } catch (Exception e) { e.printStackTrace(); } }}

class Person { private String name; private int age;

// 省略getter和setter方法}

一、什么是ObjectMapper?

如何用ObjectMapper实现Java对象的简单映射示例?

  • ObjectMapper类是Jackson库的主要类,它提供一些功能将数据集或对象转换的实现。
  • 它将使用JsonParser和JsonGenerator实例来实现JSON的实际读/写。

二、ObjectMapper怎么使用?

2.1 配置

2.1.1 普通Java项目(引入如下依赖即可)

<!-- mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.5</version> </dependency> <!-- mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.5</version> </dependency> <!-- mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.5</version> </dependency>

2.1.2 Sring Boot项目

重要说明:

由于Spring Boot的自动配置JacksonAutoConfiguration中有如下图所示的依赖引入和配置,所以不需要我们额外配置

2.2 实战

User类

@Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class User implements Serializable { private static final long serialVersionUID = 1L; // 姓名 private String name; // 性别 private String sex; // 年龄 private Integer age; }

2.2.1 Java对象、集合转JSON

public static void main(String[] args) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); User user = new User(); user.setName("张三"); user.setAge(20); user.setSex("男"); List<User> userList = new ArrayList<>(); userList.add(user); // 对象转换为JSON String userJsonString = objectMapper.writeValueAsString(user); // 集合转换为JSON String userListJsonString = objectMapper.writeValueAsString(userList); }

2.2.2 JSON转Java对象、集合

// JOSN转对象(java对象) User newUser = objectMapper.readValue(userJsonString, User.class); // JOSN转集合(集合) List<User> list = objectMapper.readValue(userListJsonString, new TypeReference<List<User>>(){});

2.2.3json转JsonNode、ObjectNode

说明:

Jackson的JsonNode和ObjectNode两个类,前者是不可变的,一般用于读取。后者可变,一般用于创建Json对象图。

// json转JsonNode JsonNode jsonNode = objectMapper.readTree(userJsonString); String sex = jsonNode.get("sex").asText(); // JsonNode转ObjectNode ObjectNode objectNode = (ObjectNode)jsonNode; // json转JsonNode JsonNode jsonNodeList = objectMapper.readTree(userListJsonString); // JsonNode转ObjectNode ArrayNode arrayNode = (ArrayNode)jsonNodeList;

2.2.4 jsonNode转对象、集合

// jsonNode转为json字符串 String jsonNodeString = objectMapper.writeValueAsString(jsonNode); String jsonNodeListString = objectMapper.writeValueAsString(jsonNodeList); // json字符串转对象、集合 User user1 = objectMapper.readValue(jsonNodeString, User.class); List<User> list1 = objectMapper.readValue(jsonNodeListString, new TypeReference<List<User>>() {});

2.3 注意事项

2.3.1微服务中从其他服务获取过来的对象,如果从Object强转为自定义的类型会报错,利用ObjectMapper转换。

正确示例:

  说明:Schedule类、OutpOrderBill类都是类似于User类的Java对象。

// 对象 Schedule schedule = objectMapper.convertValue(callNurseCenterService.getSchedule(registRecord.getScheCode()).getData(), Schedule.class); // 泛型为对象的集合 List<OutpOrderBill> outpOrderBillList = objectMapper.convertValue( callChargeCenterService.getOrderBillByOrderCode(orders.getOrgCode(),orders.getOrderCode()).getData(), new TypeReference<List<OutpOrderBill>>() {});

2.3.2 上面转换的过程中,如果返回的字段你不是都需要,需要忽略其中的几个字段,在自定义的类中添加标红注解

@Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @JsonIgnoreProperties(ignoreUnknown = true) public class User implements Serializable { private static final long serialVersionUID = 1L; ////提供有这个参数,但是不想获取 // // 姓名 // private String name; // 性别 private String sex; // 年龄 private Integer age; }

如果不想添加注解,可以使用下面两种方式

第一种方式:

ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD,Visibility.ANY); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

第二种方式:

ObjectMapper objectMapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

2.3.3 在转换的过程中,有可能有的属性被设成空就不序列化等的需求,可以在类的属性上或直接在类上加上一下注解。用在属性上就是只针对一个属性,用在类上就是针对类里的所有属性。

@JsonInclude(Include.NON_NULL) @JsonInclude(Include.Include.ALWAYS) 默认 @JsonInclude(Include.NON_DEFAULT) 属性为默认值不序列化 @JsonInclude(Include.NON_EMPTY) 属性为 空(“”) 或者为 NULL 都不序列化 @JsonInclude(Include.NON_NULL) 属性为NULL 不序列化

参考网址:

Jackson-1.9.9在线文档

到此这篇关于Java使用ObjectMapper的简单示例的文章就介绍到这了,更多相关Java使用ObjectMapper内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!

本文共计1137个文字,预计阅读时间需要5分钟。

如何用ObjectMapper实现Java对象的简单映射示例?

一、什么是ObjectMapper?

ObjectMapper是Jackson库的主要类,它提供了一些将数据集或对象转换的功能。它可以将数据集或对象转换为JSON格式,也可以将JSON字符串转换回数据集或对象。

二、ObjectMapper的使用方法

ObjectMapper的使用方法如下:

1. 创建ObjectMapper实例。

2.使用ObjectMapper的readValue方法将JSON字符串转换为对象。

3.使用ObjectMapper的writeValue方法将对象转换为JSON字符串。

示例代码:

java

import com.fasterxml.jackson.databind.ObjectMapper;

public class ObjectMapperExample { public static void main(String[] args) { try { // 创建ObjectMapper实例 ObjectMapper mapper=new ObjectMapper();

// 将JSON字符串转换为对象 String json={\name\:\John\, \age\:30}; Person person=mapper.readValue(json, Person.class);

// 将对象转换为JSON字符串 String jsonResult=mapper.writeValueAsString(person); System.out.println(jsonResult); } catch (Exception e) { e.printStackTrace(); } }}

class Person { private String name; private int age;

// 省略getter和setter方法}

一、什么是ObjectMapper?

如何用ObjectMapper实现Java对象的简单映射示例?

  • ObjectMapper类是Jackson库的主要类,它提供一些功能将数据集或对象转换的实现。
  • 它将使用JsonParser和JsonGenerator实例来实现JSON的实际读/写。

二、ObjectMapper怎么使用?

2.1 配置

2.1.1 普通Java项目(引入如下依赖即可)

<!-- mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.5</version> </dependency> <!-- mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.5</version> </dependency> <!-- mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.5</version> </dependency>

2.1.2 Sring Boot项目

重要说明:

由于Spring Boot的自动配置JacksonAutoConfiguration中有如下图所示的依赖引入和配置,所以不需要我们额外配置

2.2 实战

User类

@Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class User implements Serializable { private static final long serialVersionUID = 1L; // 姓名 private String name; // 性别 private String sex; // 年龄 private Integer age; }

2.2.1 Java对象、集合转JSON

public static void main(String[] args) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); User user = new User(); user.setName("张三"); user.setAge(20); user.setSex("男"); List<User> userList = new ArrayList<>(); userList.add(user); // 对象转换为JSON String userJsonString = objectMapper.writeValueAsString(user); // 集合转换为JSON String userListJsonString = objectMapper.writeValueAsString(userList); }

2.2.2 JSON转Java对象、集合

// JOSN转对象(java对象) User newUser = objectMapper.readValue(userJsonString, User.class); // JOSN转集合(集合) List<User> list = objectMapper.readValue(userListJsonString, new TypeReference<List<User>>(){});

2.2.3json转JsonNode、ObjectNode

说明:

Jackson的JsonNode和ObjectNode两个类,前者是不可变的,一般用于读取。后者可变,一般用于创建Json对象图。

// json转JsonNode JsonNode jsonNode = objectMapper.readTree(userJsonString); String sex = jsonNode.get("sex").asText(); // JsonNode转ObjectNode ObjectNode objectNode = (ObjectNode)jsonNode; // json转JsonNode JsonNode jsonNodeList = objectMapper.readTree(userListJsonString); // JsonNode转ObjectNode ArrayNode arrayNode = (ArrayNode)jsonNodeList;

2.2.4 jsonNode转对象、集合

// jsonNode转为json字符串 String jsonNodeString = objectMapper.writeValueAsString(jsonNode); String jsonNodeListString = objectMapper.writeValueAsString(jsonNodeList); // json字符串转对象、集合 User user1 = objectMapper.readValue(jsonNodeString, User.class); List<User> list1 = objectMapper.readValue(jsonNodeListString, new TypeReference<List<User>>() {});

2.3 注意事项

2.3.1微服务中从其他服务获取过来的对象,如果从Object强转为自定义的类型会报错,利用ObjectMapper转换。

正确示例:

  说明:Schedule类、OutpOrderBill类都是类似于User类的Java对象。

// 对象 Schedule schedule = objectMapper.convertValue(callNurseCenterService.getSchedule(registRecord.getScheCode()).getData(), Schedule.class); // 泛型为对象的集合 List<OutpOrderBill> outpOrderBillList = objectMapper.convertValue( callChargeCenterService.getOrderBillByOrderCode(orders.getOrgCode(),orders.getOrderCode()).getData(), new TypeReference<List<OutpOrderBill>>() {});

2.3.2 上面转换的过程中,如果返回的字段你不是都需要,需要忽略其中的几个字段,在自定义的类中添加标红注解

@Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @JsonIgnoreProperties(ignoreUnknown = true) public class User implements Serializable { private static final long serialVersionUID = 1L; ////提供有这个参数,但是不想获取 // // 姓名 // private String name; // 性别 private String sex; // 年龄 private Integer age; }

如果不想添加注解,可以使用下面两种方式

第一种方式:

ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD,Visibility.ANY); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

第二种方式:

ObjectMapper objectMapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

2.3.3 在转换的过程中,有可能有的属性被设成空就不序列化等的需求,可以在类的属性上或直接在类上加上一下注解。用在属性上就是只针对一个属性,用在类上就是针对类里的所有属性。

@JsonInclude(Include.NON_NULL) @JsonInclude(Include.Include.ALWAYS) 默认 @JsonInclude(Include.NON_DEFAULT) 属性为默认值不序列化 @JsonInclude(Include.NON_EMPTY) 属性为 空(“”) 或者为 NULL 都不序列化 @JsonInclude(Include.NON_NULL) 属性为NULL 不序列化

参考网址:

Jackson-1.9.9在线文档

到此这篇关于Java使用ObjectMapper的简单示例的文章就介绍到这了,更多相关Java使用ObjectMapper内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!