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);
原文地址:https://www.cnblogs.com/Big-Boss/p/14845851.html