>

Jackjson之ObjectMapper

简介

ObjectMapper类(com.fasterxml.jackson.databind.ObjectMapper)是Jackson的主要类,它可以帮助我们快速的进行各个类型和Json类型的相互转换。

使用

1、引入Jackson的依赖

复制代码
<!-- 根据自己需要引入相关版本依赖。 -->
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.9.10</version>
</dependency>
 
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.10</version>
</dependency>
 
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>2.9.10</version>
</dependency>
复制代码

2、ObjectMapper的常用配置

复制代码
private static final ObjectMapper mapper;
 
public static ObjectMapper getObjectMapper(){
    return this.mapper;
}
 
static{
    //创建ObjectMapper对象
    mapper = new ObjectMapper()
 
    //configure方法 配置一些需要的参数
    // 转换为格式化的json 显示出来的格式美化
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
 
   //序列化的时候序列对象的那些属性  
   //JsonInclude.Include.NON_DEFAULT 属性为默认值不序列化 
   //JsonInclude.Include.ALWAYS      所有属性
   //JsonInclude.Include.NON_EMPTY   属性为 空(“”) 或者为 NULL 都不序列化 
   //JsonInclude.Include.NON_NULL    属性为NULL 不序列化
   mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);  
 
   
    //反序列化时,遇到未知属性会不会报错 
    //true - 遇到没有的属性就报错 false - 没有的属性不会管,不会报错
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
    //如果是空对象的时候,不抛异常  
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);  
 
    // 忽略 transient 修饰的属性
    mapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true);
 
    //修改序列化后日期格式
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);  
    mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
 
   //处理不同的时区偏移格式
   mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
   mapper.registerModule(new JavaTimeModule());
 
}
复制代码

如果不需要特殊配置可以直接使用原生的ObjectMapper类即可。

3、ObjectMapper的常用方法

a.json字符串转对象

复制代码
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"Hyl\", \"age\":20}";
 
//将字符串转换为对象
Student student = mapper.readValue(jsonString, Student.class);
System.out.println(student);
 
//将对象转换为json字符串
jsonString = mapper.writeValueAsString(student);
System.out.println(jsonString);
 
 
结果:
Student [ name: Hyl, age: 20 ]
 
{
  "name" : "Hyl",
  "age" : 20
}
 
复制代码

b. 数组和对象之间转换

复制代码
//对象转为byte数组
byte[] byteArr = mapper.writeValueAsBytes(student);
System.out.println(byteArr);
 
 
//byte数组转为对象
Student student= mapper.readValue(byteArr, Student.class);
System.out.println(student);
 
结果:
[B@3327bd23
 
Student [ name: Hyl, age: 20 ]
复制代码

c. 集合和json字符串之间转换

复制代码
List<Student> studentList= new ArrayList<>();
studentList.add(new Student("hyl1" ,20 , new Date()));
studentList.add(new Student("hyl2" ,21 , new Date()));
studentList.add(new Student("hyl3" ,22 , new Date()));
studentList.add(new Student("hyl4" ,23 , new Date()));
 
String jsonStr = mapper.writeValueAsString(studentList);
System.out.println(jsonStr);
        
List<Student> studentList2 = mapper.readValue(jsonStr, List.class);
System.out.println("字符串转集合:" + studentList2 );
 
结果:
[ {
  "name" : "hyl1",
  "age" : 20,
  "sendTime" : 1525164212803
}, {
  "name" : "hyl2",
  "age" : 21,
  "sendTime" : 1525164212803
}, {
  "name" : "hyl3",
  "age" : 22,
  "sendTime" : 1525164212803
}, {
  "name" : "hyl4",
  "age" : 23,
  "sendTime" : 1525164212803
} ]
[{name=hyl1, age=20, sendTime=1525164212803}, {name=hyl2, age=21, sendTime=1525164212803}, {name=hyl3, age=22, sendTime=1525164212803}, {name=hyl4, age=23, sendTime=1525164212803}]
复制代码

d. map和json字符串之间转换

复制代码
Map<String, Object> testMap = new HashMap<>();
testMap.put("name", "22");
testMap.put("age", 20);
testMap.put("date", new Date());
testMap.put("student", new Student("hyl", 20, new Date()));
 
 
String jsonStr = mapper.writeValueAsString(testMap);
System.out.println(jsonStr);
Map<String, Object> testMapDes = mapper.readValue(jsonStr, Map.class);
System.out.println(testMapDes);
 
结果:
{
  "date" : 1525164212803,
  "name" : "22",
  "student" : {
    "name" : "hyl",
    "age" : 20,
    "sendTime" : 1525164212803,
    "intList" : null
  },
  "age" : 20
}
{date=1525164212803, name=22, student={name=hyl, age=20, sendTime=1525164212803, intList=null}, age=20}
复制代码

e. 日期转json字符串

复制代码
// 修改时间格式
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
Student student = new Student ("hyl",21, new Date());
student.setIntList(Arrays.asList(1, 2, 3));
 
String jsonStr = mapper.writeValueAsString(student);
System.out.println(jsonStr);
 
结果:
{
  "name" : "hyl",
  "age" : 21,
  "sendTime" : "2020-07-23 13:14:36",
  "intList" : [ 1, 2, 3 ]
}
复制代码

 

 

参考文章:

https://blog.csdn.net/qq_42017395/article/details/107555339

posted @   字节悦动  阅读(630)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示

目录导航