ObjectMapper类

前言

ObjectMapper类是Jackson库的主要类。它提供一些功能将转换成Java对象匹配JSON结构,反之亦然

使用方式

使用Jackson,首先需要相关的jar包。对于使用maven的,需要添加以下依赖:

<!-- 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>

  

实例演示

Java对象转换为JSON对象 json对象转化为java 对象

ObjectMapper objectMapper = new ObjectMapper(); 
 
        //序列化的时候序列对象的所有属性 
        objectMapper.setSerializationInclusion(Include.ALWAYS); 
 
		// 如果json中有新增的字段并且是实体类类中不存在的,不报错
        //objectMapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //反序列化的时候如果多了其他属性,不抛出异常 
        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")) 

  PS:还需要注意,如果ObjectMapper的configure设置FAIL_ON_EMPTY_BEANS为false,那么对应的实体类的属性没有get方法也不会抛出异常,但是这个属性默认的是true,即必须要有get方法,这个需要注意。

public class ObjectMapperTest {
 
    public static void main(String[] args) throws IOException {
 
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, true);
        Person person = new Person(1, "tom", "123");
        String jsonString = objectMapper.writeValueAsString(person);
        System.out.println("JsonString: " + jsonString);
 
        Person person1 = objectMapper.readValue(jsonString, Person.class);
        System.out.println(person1.toString());
 
    }
 
}

Java数组对象和JSON数组对象之间的转换

public static void getListData() {
       ObjectMapper objectMapper = new ObjectMapper();
       //Java数组转换为JSON数组
       Person person = new Person(1, "tom", "123");
       Person person1 = new Person(2, "jack", "123445");
       List<Person> personList = new ArrayList<>();
       personList.add(person);
       personList.add(person1);
       String jsonString = null;
       try {
           //Json数组转换为Java数组
           jsonString = objectMapper.writeValueAsString(personList);
           System.out.println("JsonString List: " + jsonString);
           //JavaType
           JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, Person.class);
           List<Person> list = objectMapper.readValue(jsonString, javaType);
           //打印出list中的值
           for (Person person2 : list) {
               System.out.println(person2.toString());
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
   }

参考:

  • 封装对象User
package com.entity;
import java.io.Serializable;
public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    private String userName;
    private String age;
    private String sex;
    private String email;
    private String phone;
    public User() {
        super();
    }
    public User(String userName, String age, String sex, String email, String phone) {
        super();
        this.userName = userName;
        this.age = age;
        this.sex = sex;
        this.email = email;
        this.phone = phone;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    @Override
    public String toString() {
        return "User{" +
                "userName='" + userName + '\'' +
                ", age='" + age + '\'' +
                ", sex='" + sex + '\'' +
                ", email='" + email + '\'' +
                ", phone='" + phone + '\'' +
                '}';
    }
}
  • ObjectMapper 对象预处理
public static ObjectMapper mapper = new ObjectMapper();
    //涉及到一下问题需要预处理,否则直接在引用时new new ObjectMapper();即可
    static {
        // 转换为格式化的json
        mapper .enable( SerializationFeature.INDENT_OUTPUT);
        // 如果json中有新增的字段并且是实体类类中不存在的,不报错
        mapper .configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }
  • ObjectMapper -> write (写)
//将对象信息写入指定文件
mapper.writeValue(new File("C:\\Users\\Chyb\\Desktop\\新建文本文档.txt"), user);
//将对象信息写到控制台
mapper.writeValue(System.out, user);
//将Map对象转换为JSON字符串(对象为Object对象,均可以转换为JOSN串)
String str = mapper.writeValueAsString( map )
String str = objectMapper.writeValueAsString( list );
//将对象转换为JSON串,依赖于对象中封装的get、set方法(没有get、set方法会报JSON转换异常)
String userJSON = mapper.writeValueAsString( user );
//将对象转换为byte数组
byte[] bytes = objectMapper.writeValueAsBytes( u );
//如果转换的对象中有日期元素,在mapper对象中填装时间格式化属性,那么接下来用mapper对下对象转换过的对象,转换后时间元素会被格式化,如果在填装时间格式化属性之前则不会格式化生效
mapper.setDateFormat( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

  • ObjectMapper -> read (读)
//读取JSON数据转换实体对象,依赖于实体对象的无参构造方法,无参构造方法不存在则会报JSON序列化异常
User u = mapper.readValue( userJSON, User.class );
//读取文件内容,转换为实体对象
User fileUser = objectMapper.readValue( new File( "C:\\Users\\Chyb\\Desktop\\新建文本文档.txt" ), User.class );
//读取文件内容,转换为Map对象
Map map = objectMapper.readValue( new File( "C:\\Users\\Chyb\\Desktop\\新建文本文档.txt" ), Map.class );
//读取byte数组,填装至实体对象
User user = objectMapper.readValue( bytes, User.class );

参考原文:https://blog.csdn.net/scdncby/article/details/83506619

posted @ 2022-09-12 22:40  哩个啷个波  阅读(179)  评论(0编辑  收藏  举报