zoukankan      html  css  js  c++  java
  • Java 对象与json互转之ObjectMapper

    一、使用ObjectMapper

      引入ObjectMapper依赖:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.3</version>
    </dependency>

      使用时先创建ObjectMapper对象

    ObjectMapper objectMapper = new ObjectMapper();

      根据代码实际需求情况可设置定义下面属性:

    //序列化的时候序列对象的所有属性
    objectMapper.setSerializationInclusion(Include.ALWAYS);
    
    //反序列化的时候如果多了其他属性,不抛出异常
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    
    //如果是空对象的时候,不抛异常
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    
    //取消时间的转化格式,默认是时间戳,可以取消,同时需要设置要表现的时间格式
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

      1、对象与json字符串互转

    // 学生对象
    Student student = new Student();
    
    // 对象转json字符串
    String jsonStr = mapper.writeValueAsString(student);
    
    // json字符串转对象
    Student student = mapper.readValue(jsonStr, Student.class);

      2、对象与byte数组互转

    // 学生对象
    Student student = new Student();
    
    // 对象转byte数组
    byte[] byteArr = mapper.writeValueAsBytes(student);
    
    // byte数组转对象
    Student student = mapper.readValue(byteArr, Student.class);

      3、对象List集合与json字符串

    // 学生对象List集合
    List<Student> studentList = new ArrayList<>();
    
    // 对象List集合转json字符串
    String jsonStr = mapper.writeValueAsString(studentList);
    
    // json字符串转对象List集合
    List<Student> studentList = mapper.readValue(jsonStr, List.class);

      4、Map与json字符串

    Map<String, Object> testMap = new HashMap<>();
    
    // Map转json字符串
    String jsonStr = mapper.writeValueAsString(testMap);
    
    // json字符串转Map
    Map<String, Object> testMap = mapper.readValue(jsonStr, Map.class);
  • 相关阅读:
    【转】Python爬虫(5)_性能相关
    【转】Python爬虫(4)_selenium模块
    【转】Python爬虫(3)_Beautifulsoup模块
    【转】Python爬虫_示例2
    【转】Python爬虫_示例
    linux开机自启动tomcat
    Linux下Tomcat启动,停止命令
    Linux下tomcat启动Neither the JAVA_HOME nor the JRE_HOME environment variable is defined At least one of
    centos7开启关闭80端口
    centos安装JDK
  • 原文地址:https://www.cnblogs.com/Big-Boss/p/14845851.html
Copyright © 2011-2022 走看看