zoukankan      html  css  js  c++  java
  • Java使用ObjectMapper的简单示例

    一、什么是ObjectMapper?

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

    二、ObjectMapper怎么使用?

    2.1 配置

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

    <!-- https://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>
     
    <!-- https://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>
     
    <!-- https://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类

     1 @Data
     2 @EqualsAndHashCode(callSuper = false)
     3 @Accessors(chain = true)
     4 public class User implements Serializable {
     5 
     6     private static final long serialVersionUID = 1L;
     7 
     8     // 姓名
     9     private String name;
    10 
    11     // 性别
    12     private String sex;
    13 
    14     // 年龄
    15     private Integer age;
    16 }

    2.2.1 Java对象、集合转JSON

     1 public static void main(String[] args) throws IOException {
     2 
     3         ObjectMapper objectMapper = new ObjectMapper();
     4 
     5         User user = new User();
     6         user.setName("张三");
     7         user.setAge(20);
     8         user.setSex("男");
     9 
    10         List<User> userList = new ArrayList<>();
    11         userList.add(user);
    12 
    13         // 对象转换为JSON
    14         String userJsonString = objectMapper.writeValueAsString(user);16 
    17         // 集合转换为JSON
    18         String userListJsonString = objectMapper.writeValueAsString(userList);20 }

    2.2.2 JSON转Java对象、集合

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

    2.2.3 json转JsonNode、ObjectNode

    说明:

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

     1      // json转JsonNode
     2         JsonNode jsonNode = objectMapper.readTree(userJsonString);
     3         String sex = jsonNode.get("sex").asText();
     4 
     5         // JsonNode转ObjectNode
     6         ObjectNode objectNode = (ObjectNode)jsonNode;
     7 
     8         // json转JsonNode
     9         JsonNode jsonNodeList = objectMapper.readTree(userListJsonString);
    10 
    11         // JsonNode转ObjectNode
    12         ArrayNode arrayNode = (ArrayNode)jsonNodeList;

     2.2.4 jsonNode转对象、集合

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

    2.2.5 遇到对象有属性是日期的,可以对ObjectMapper进行个性化设置

    // 设置时间格式信息
    objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

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

     1 @Data
     2 @EqualsAndHashCode(callSuper = false)
     3 @Accessors(chain = true)
     4 @JsonIgnoreProperties(ignoreUnknown = true)
     5 public class User  implements Serializable {
     6 
     7     private static final long serialVersionUID = 1L;
     8 
     9      ////提供有这个参数,但是不想获取
    10 //    // 姓名
    11 //    private String name;
    12 
    13     // 性别
    14     private String sex;
    15 
    16     // 年龄
    17     private Integer age;
    18 }

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

    第一种方式:

    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在线文档

  • 相关阅读:
    C++(封装一)
    数据结构之链式栈(二)
    C++(函数重载二)
    不计算阶乘获得结果末尾0的个数
    附加产品
    刘子闻讲的高精度【太强了】
    字符串相关函数
    回文素数
    蛇形填数
    筛法模版
  • 原文地址:https://www.cnblogs.com/wgx519/p/13688615.html
Copyright © 2011-2022 走看看