Jackson库中objectMapper的用法
作者:老周聊架构 发布时间:2023-10-25 13:20:40
Jackson库中objectMapper用法
ObjectMapper类是Jackson库的主要类。它提供一些功能将转换成Java对象与SON结构互相转换,在项目中遇到过,故记录一下。
在 pom.xml 加入依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.3</version>
</dependency>
创建一个实体类RiemannUser:
package com.test.objectMapper;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* @author riemann
* @date 2019/05/27 22:48
*/
public class RiemannUser implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String message;
private Date sendDate;
private String nodeName;
private List<Integer> intList;
public RiemannUser() {
super();
}
public RiemannUser(int id, String message, Date sendDate) {
super();
this.id = id;
this.message = message;
this.sendDate = sendDate;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getSendDate() {
return sendDate;
}
public void setSendDate(Date sendDate) {
this.sendDate = sendDate;
}
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public List<Integer> getIntList() {
return intList;
}
public void setIntList(List<Integer> intList) {
this.intList = intList;
}
@Override
public String toString() {
return "RiemannUser{" + "id=" + id + ", message='" + message + '\'' + ", sendDate=" + sendDate + ", nodeName='" + nodeName + '\'' + ", intList=" + intList + '}';
}
}
先创建一个ObjectMapper,然后赋值一些属性:
public static ObjectMapper mapper = new ObjectMapper();
static {
// 转换为格式化的json
mapper.enable(SerializationFeature.INDENT_OUTPUT);
// 如果json中有新增的字段并且是实体类类中不存在的,不报错
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
1、对象与json字符串、byte数组
@Test
public void testObject() throws JsonGenerationException, JsonMappingException, IOException {
RiemannUser riemann = new RiemannUser(1,"Hello World", new Date());
mapper.writeValue(new File("D:/test.txt"), riemann);//写到文件中
//mapper.writeValue(System.out, riemann); //写到控制台
String jsonStr = mapper.writeValueAsString(riemann);
System.out.println("对象转json字符串: " + jsonStr);
byte[] byteArr = mapper.writeValueAsBytes(riemann);
System.out.println("对象转为byte数组:" + byteArr);
RiemannUser riemannUser = mapper.readValue(jsonStr, RiemannUser.class);
System.out.println("json字符串转为对象:" + riemannUser);
RiemannUser riemannUser2 = mapper.readValue(byteArr, RiemannUser.class);
System.out.println("byte数组转为对象:" + riemannUser2);
}
运行结果:
对象转json字符串: {
"id" : 1,
"message" : "Hello World",
"sendDate" : 1558971056693,
"nodeName" : null,
"intList" : null
}
对象转为byte数组:[B@31610302
json字符串转为对象:RiemannUser{id=1, message='Hello World', sendDate=Mon May 27 23:30:56 CST 2019, nodeName='null', intList=null}
byte数组转为对象:RiemannUser{id=1, message='Hello World', sendDate=Mon May 27 23:30:56 CST 2019, nodeName='null', intList=null}
2、list集合与json字符串
@Test
public void testList() throws JsonGenerationException, JsonMappingException, IOException {
List<RiemannUser> riemannList = new ArrayList<>();
riemannList.add(new RiemannUser(1,"a",new Date()));
riemannList.add(new RiemannUser(2,"b",new Date()));
riemannList.add(new RiemannUser(3,"c",new Date()));
String jsonStr = mapper.writeValueAsString(riemannList);
System.out.println("集合转为字符串:" + jsonStr);
List<RiemannUser> riemannLists = mapper.readValue(jsonStr, List.class);
System.out.println("字符串转集合:" + riemannLists);
}
运行结果:
集合转为字符串:[ {
"id" : 1,
"message" : "a",
"sendDate" : 1558971833351,
"nodeName" : null,
"intList" : null
}, {
"id" : 2,
"message" : "b",
"sendDate" : 1558971833351,
"nodeName" : null,
"intList" : null
}, {
"id" : 3,
"message" : "c",
"sendDate" : 1558971833351,
"nodeName" : null,
"intList" : null
} ]
字符串转集合:[{id=1, message=a, sendDate=1558971833351, nodeName=null, intList=null}, {id=2, message=b, sendDate=1558971833351, nodeName=null, intList=null}, {id=3, message=c, sendDate=1558971833351, nodeName=null, intList=null}]
3、map与json字符串
@Test
public void testMap() {
Map<String, Object> testMap = new HashMap<>();
testMap.put("name", "riemann");
testMap.put("age", 27);
testMap.put("date", new Date());
testMap.put("user", new RiemannUser(1, "Hello World", new Date()));
String jsonStr = null;
try {
jsonStr = mapper.writeValueAsString(testMap);
System.out.println("Map转为字符串:" + jsonStr);
Map<String, Object> testMapDes = null;
try {
testMapDes = mapper.readValue(jsonStr, Map.class);
System.out.println("字符串转Map:" + testMapDes);
} catch (IOException e) {
e.printStackTrace();
}
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
Map转为字符串:{
"date" : 1558972169132,
"name" : "riemann",
"user" : {
"id" : 1,
"message" : "Hello World",
"sendDate" : 1558972169134,
"nodeName" : null,
"intList" : null
},
"age" : 27
}
字符串转Map:{date=1558972169132, name=riemann, user={id=1, message=Hello World, sendDate=1558972169134, nodeName=null, intList=null}, age=27}
4、修改转换时的日期格式:
@Test
public void testOther() throws IOException {
// 修改时间格式
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
RiemannUser riemannUser = new RiemannUser(1,"Hello World",new Date());
riemannUser.setIntList(Arrays.asList(1,2,3));
String jsonStr = mapper.writeValueAsString(riemannUser);
System.out.println("对象转为字符串:" + jsonStr);
}
运行结果:
对象转为字符串:{
"id" : 1,
"message" : "Hello World",
"sendDate" : "2019-05-27 23:53:55",
"nodeName" : null,
"intList" : [ 1, 2, 3 ]
}
objectMapper的一些坑
相信做过Java 开发对这个类应该不陌生,没错,这个类是jackson提供的,主要是用来把对象转换成为一个json字符串返回到前端,
现在大部分数据交换都是以json来传输的,所以这个很重要,那你到底又对这个类有着有多少了解呢,下面我说一下我遇到的一些坑
首先,先把我要说的几个坑需要设置的属性贴出来先
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"))
简单说一下这个类的基本用法,以下采用代码块加截图的形式来说明和部分文字件数
package com.shiro.test;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class Main2 {
public static void main(String[] args) throws Exception{
ObjectMapper objectMapper = new ObjectMapper();
//序列化的时候序列对象的所有属性
objectMapper.setSerializationInclusion(Include.ALWAYS);
//取消时间的转化格式,默认是时间戳,可以取消,同时需要设置要表现的时间格式
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
Person person = new Person(1, "zxc", new Date());
//这是最简单的一个例子,把一个对象转换为json字符串
String personJson = objectMapper.writeValueAsString(person);
System.out.println(personJson);
//默认为true,会显示时间戳
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
personJson = objectMapper.writeValueAsString(person);
System.out.println(personJson);
}
}
输出的信息如下
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)的作用
package com.shiro.test;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class Main2 {
public static void main(String[] args) throws Exception{
ObjectMapper objectMapper = new ObjectMapper();
//序列化的时候序列对象的所有属性
objectMapper.setSerializationInclusion(Include.ALWAYS);
//如果是空对象的时候,不抛异常,也就是对应的属性没有get方法
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
Person person = new Person(1, "zxc", new Date());
String personJson = objectMapper.writeValueAsString(person);
System.out.println(personJson);
//默认是true,即会抛异常
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, true);
personJson = objectMapper.writeValueAsString(person);
System.out.println(personJson);
}
}
对应的person类此时为
package com.shiro.test;
import java.util.Date;
public class Person {
private Integer id;
private String name;
private Date birthDate;
//public Integer getId() {
//return id;
//}
//public void setId(Integer id) {
//this.id = id;
//}
//public String getName() {
//return name;
//}
//public void setName(String name) {
//this.name = name;
//}
//public Date getBirthDate() {
//return birthDate;
//}
//public void setBirthDate(Date birthDate) {
//this.birthDate = birthDate;
//}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", birthDate=" + birthDate + "]";
}
public Person(Integer id, String name, Date birthDate) {
super();
this.id = id;
this.name = name;
this.birthDate = birthDate;
}
public Person() {
// TODO Auto-generated constructor stub
}
}
结果如下
package com.shiro.test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main2 {
public static void main(String[] args) throws Exception{
ObjectMapper objectMapper = new ObjectMapper();
//序列化的时候序列对象的所有属性
objectMapper.setSerializationInclusion(Include.ALWAYS);
//反序列化的时候如果多了其他属性,不抛出异常
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//Person person = new Person(1, "zxc", new Date());
//String personJson = objectMapper.writeValueAsString(person);
//System.out.println(personJson);
//注意,age属性是不存在在person对象中的
String personStr = "{\"id\":1,\"name\":\"zxc\",\"age\":\"zxc\"}";
Person person = objectMapper.readValue(personStr, Person.class);
System.out.println(person);
//默认为true
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
person = objectMapper.readValue(personStr, Person.class);
System.out.println(person);
}
}
执行后的结果如下
这些便是这几个属性的作用所以,由于第一个比较简单我就这样说一下吧
Include.ALWAYS 是序列化对像所有属性
Include.NON_NULL 只有不为null的字段才被序列化
Include.NON_EMPTY 如果为null或者 空字符串和空集合都不会被序列化
然后再说一下如何把一个对象集合转换为一个 Java里面的数组
package com.shiro.test;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main2 {
public static void main(String[] args) throws Exception{
ObjectMapper objectMapper = new ObjectMapper();
//序列化的时候序列对象的所有属性
objectMapper.setSerializationInclusion(Include.NON_DEFAULT);
Person person1 = new Person(1, "zxc", new Date());
Person person2 = new Person(2, "ldh", new Date());
List<Person> persons = new ArrayList<>();
persons.add(person1);
persons.add(person2);
//先转换为json字符串
String personStr = objectMapper.writeValueAsString(persons);
//反序列化为List<user> 集合,1需要通过 TypeReference 来具体传递值
List<Person> persons2 = objectMapper.readValue(personStr, new TypeReference<List<Person>>() {});
for(Person person : persons2) {
System.out.println(person);
}
//2,通过 JavaType 来进行处理返回
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, Person.class);
List<Person> persons3 = objectMapper.readValue(personStr, javaType);
for(Person person : persons3) {
System.out.println(person);
}
}
}
来源:https://riemann.blog.csdn.net/article/details/90614414


猜你喜欢
- activity动画方式在AndroidMenifest中添加activity的动画属性windowAnimationStyle <i
- 这篇文章中我们来继续学习Picasso中还提供了哪些扩展功能,一个好的框架一定是扩展性强的,你需要的我刚好有。下面看一下都提供了哪些扩展功能
- 在C#中,一共有38个常用的运用符,根据它们所执行运算的特点和它们的优先级,为了便于记忆,我将它们归为七个等级:1、单元运算符和括号。2、常
- 本文实例实现一个启动画面,采用了显示Aform,过一段时间,隐藏这个Aform,showdialog下一个Bform,closeAForm这
- 一、在学习枚举之前,首先来听听枚举的优点。1、枚举能够使代码更加清晰,它允许使用描述性的名称表示整数值。2、枚举使代码更易于维护,有助于确保
- okio库的类结构okio 主要的接口和类okio接口和类的说明名称类型描述Source接口定义了输入流的几个基本方法BufferedSou
- 扫雷游戏,大家都应该玩过吧!其实规则也很简单,可是我们想自己实现一个扫雷,我们应该怎么做呢?Step1: 知晓游戏原理扫雷就是要把所有非地雷
- 本文实例为大家分享了Android仿京东左侧分类条目效果的具体代码,供大家参考,具体内容如下import android.app.Activ
- 一个线程如何知道另一线程已经结束?Thread类提供了回答此问题的方法。有两种方法可以判定一个线程是否结束。第一,可以在线程中调用isAli
- 下面一段代码给大家分享了android中判断手机是否安装了qq或者微信,代码简单易懂,非常不错,具有参考借鉴价值,需要的的朋友参考下吧pub
- 本文实例讲述了Java基于命令模式实现邮局发信功能。分享给大家供大家参考,具体如下:一. 模式定义命令模式,将来自客户端的请求封建为一个对象
- 如下,可以使用C#的Replace()方法来替换,但有一点需要注意的是backslash(反斜杠)是特殊字符。string s = &quo
- 程序的结构分类:顺序结构:按照写代码的顺序 一次执行选择结构:根据条件的不同有选择的执行不同的代码循环结构:在一定条件下 反复执行某一片代码
- 前言:在我们使用C# WinForm中,我们有时候是需要或者自己本机的IP地址进行处理,今天我们学习一下如何使用C# Winform获取主机
- 一、前言在mybatis官网中,有插件一说 mybatis plugins 如果同时有多个插件,那么他们的执行顺序是怎样的?二、准备工作、代
- 一、SpringMvc概述SpringMVC是一个基于MVC设计模式的WEB层框架。SpringMVC设计模式:MVC,全名是(Model
- Java内部类一、 含义在Java编程语言里,程序是由类(class)构建而成的。在一个类的内部也可以声明类,我们把这样的类叫做内部类。二、
- maven使用过程中无法导入依赖的一些总结作为一名java开发的新手,在学习中难免遇见各种问题,在此总结一下。在使用maven过程中总是碰见
- 一、开源项目 Javascript .NET地址: http://javascriptdotnet.codeplex.com/ 它是Goog
- 一、什么是网关限流:在微服务架构中,网关层可以屏蔽外部服务直接对内部服务进行调用,对内部服务起到隔离保护的作用,网关限流,顾名思义,就是通过