广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Jackson库中objectMapper的用法
  • 619
分享到

Jackson库中objectMapper的用法

2024-04-02 19:04:59 619人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

Jackson库中objectMapper用法 ObjectMapper类是Jackson库的主要类。它提供一些功能将转换成Java对象与SON结构互相转换,在项目中遇到过,故记录一

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;

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);
		}
	}
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: Jackson库中objectMapper的用法

本文链接: https://www.lsjlt.com/news/128600.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Jackson库中objectMapper的用法
    Jackson库中objectMapper用法 ObjectMapper类是Jackson库的主要类。它提供一些功能将转换成Java对象与SON结构互相转换,在项目中遇到过,故记录一...
    99+
    2022-11-12
  • 详解Jackson的基本用法
    目录一、前言二、Jackson的核心模块三、ObjectMapper的使用四、信息配置五、Jackson注解的使用六、Jackson示例6.1、Jackson ObjectMappe...
    99+
    2022-11-12
  • SpringBoot中Jackson日期格式化的方法
    这篇“SpringBoot中Jackson日期格式化的方法”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“SpringBoot...
    99+
    2023-06-30
  • SpringBoot利用jackson格式化时间的三种方法
    前言 在实际开发中我们经常会与时间打交道,那这就会涉及到一个时间格式转换的问题。接下来会介绍几种在SpirngBoot中如何对时间格式进行转换。 准备工作 创建项目,添加依赖 ...
    99+
    2022-11-12
  • Java中常用解析工具jackson及fastjson的使用
    一、maven安装jackson依赖 <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/...
    99+
    2022-11-12
  • jackson在springboot中的使用方式-自定义参数转换器
    目录springboot jackson使用-自定义参数转换器要实现的功能思路关键代码Jackson自定义转换器@JsonDeserialize注解源码以日期类型为例自定义转换方法s...
    99+
    2022-11-12
  • python中PaddleOCR库的用法
    这篇文章主要讲解了“python中PaddleOCR库的用法”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“python中PaddleOCR库的用法”吧!说明PaddleOCR是基于深度学习的...
    99+
    2023-06-20
  • golang中实用库gotable的用法
    这篇文章将为大家详细讲解有关golang中实用库gotable的用法,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。一 背景在使用cli打印结果的时候,对结果进行格式化输出,但限于内容较长的,不好自动排版,...
    99+
    2023-06-20
  • 详解python中flask_caching库的用法
    目录安装flask_caching库:缓存类型配置参数初始化使用缓存为了尽量减少缓存穿透,并同时减少web的响应时间,可以针对那些需要一定时间才能获取结果的函数和那些不需要频繁更新的...
    99+
    2023-05-19
    python flask flask_caching库
  • go原生库的中bytes.Buffer用法
    1 bytes.Buffer定义 bytes.Buffer提供可扩容的字节缓冲区,实质是对切片的封装;结构中包含一个64字节的小切片,避免小内存分配: // A Buffer...
    99+
    2022-06-07
    buffer GO bytes
  • 数据库中inner join的用法
    本篇文章为大家展示了数据库中inner join的用法,代码简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。INNER JOIN是在表中存在至少一个匹配时,关键字返回行。具...
    99+
    2022-10-18
  • Python中selenium库的用法详解
    selenium主要是用来做自动化测试,支持多种浏览器,爬虫中主要用来解决JavaScript渲染问题。 模拟浏览器进行网页加载,当requests,urllib无法正常获取网页内容的时候 一、声明浏览器对象 注意点...
    99+
    2022-06-02
    Python中selenium库的用法 selenium用法 Python webdriver selenium获取网页代码 selenium执行JavaScript selenium等待 Cooki
  • Python中jieba库的使用方法
    目录一、jieba库的安装二、jieba三种模式的使用三、jieba 分词简单应用四、扩展:英文单词统计jieba库是一款优秀的 Python 第三方中文分词库,jieba 支持三种分词模式:精确模式、全模式和搜索引...
    99+
    2022-06-02
    Python jieba库
  • JS库中Three.js的用法示例
    这篇文章给大家分享的是有关JS库中Three.js的用法示例的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。准备工作在写代码之前,你首先要去下最新的three.js框架包,在你的页...
    99+
    2022-10-19
  • Python中requests库的用法详解
    目录一、requests库安装请求响应二、发送get请求1、一个带参数的get请求:2、响应json3、添加头信息headers4、添加和获取cookie信息三、发送post请求1、...
    99+
    2022-11-11
  • python中gevent库的用法详情
    目录前言: 1、gevent库可以轻松实现并发同步或异步编程。gevent中使用的主要模式是Greenlet,它是以C扩展模块的形式访问Python的轻量级协程。2、Greenlet...
    99+
    2022-11-11
  • Rx.NET库中IDisposable对象的用法
    IDisposable是.net中的主动资源释放接口,它是在编程过程中经常使用到的一个接口,本文介绍一下微软在Rx.NET中提供的一系列常用的Disposable类,通过它们可以简化...
    99+
    2022-11-13
  • springboot中关于继承WebMvcConfigurationSupport后自定义的全局Jackson失效解决方法,localdate返回数组问题
    一般情况下我们在config里增加jackson的全局配置文件就能满足基本的序列化需求,比如前后端传参的问题。 @Configurationpublic class JacksonConfig { public static fina...
    99+
    2023-08-30
    spring boot 后端 java
  • c++中loki库的用法是什么
    Loki是一个开源的C++库,提供了一些通用的设计模式和工具,用于简化C++编程。下面是一些常见的Loki库的用法: Singl...
    99+
    2023-10-25
    c++ loki
  • python中selenium库的用法是什么
    Selenium是一个用于自动化web浏览器的库,可以使用它来模拟用户在浏览器中的操作,例如点击按钮、填写表单、导航到不同的页面等。...
    99+
    2023-10-25
    python selenium
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作