使用objectMapper处理数据之间的转化详解

2024-03-19 18:38

本文主要是介绍使用objectMapper处理数据之间的转化详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在项目中使用到了ObjectMapper,故研究了一下。现将自己的几个测试用例和大家分享一下~

首先在pom.xml文件中,加入依赖:

    <dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.8.3</version></dependency>

创建一个实体类XwjUser:

public class XwjUser implements Serializable {private static final long serialVersionUID = 1L;private int id;private String message;private Date sendTime;// 这里手写字母大写,只是为了测试使用,是不符合java规范的private String NodeName;private List<Integer> intList;public XwjUser() {super();}public XwjUser(int id, String message, Date sendTime) {super();this.id = id;this.message = message;this.sendTime = sendTime;}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 getSendTime() {return sendTime;}public void setSendTime(Date sendTime) {this.sendTime = sendTime;}public String getNodeName() {return NodeName;}public void setNodeName(String nodeName) {NodeName = nodeName;}public List<Integer> getIntList() {return intList;}public void setIntList(List<Integer> intList) {this.intList = intList;}@Overridepublic String toString() {return "XwjUser [id=" + id + ", message=" + message + ", sendTime=" + sendTime + ", intList=" + intList + "]";}}

先创建一个ObjectMapper,然后赋值一些属性:

public static ObjectMapper mapper = new ObjectMapper();static {// 转换为格式化的jsonmapper.enable(SerializationFeature.INDENT_OUTPUT);// 如果json中有新增的字段并且是实体类类中不存在的,不报错mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}

1、对象与json字符串、byte数组

@Testpublic void testObj() throws JsonGenerationException, JsonMappingException, IOException {XwjUser user = new XwjUser(1, "Hello World", new Date());mapper.writeValue(new File("D:/test.txt"), user); // 写到文件中// mapper.writeValue(System.out, user); //写到控制台String jsonStr = mapper.writeValueAsString(user);System.out.println("对象转为字符串:" + jsonStr);byte[] byteArr = mapper.writeValueAsBytes(user);System.out.println("对象转为byte数组:" + byteArr);XwjUser userDe = mapper.readValue(jsonStr, XwjUser.class);System.out.println("json字符串转为对象:" + userDe);XwjUser useDe2 = mapper.readValue(byteArr, XwjUser.class);System.out.println("byte数组转为对象:" + useDe2);}

运行结果:

对象转为字符串:{"id" : 1,"message" : "Hello World","sendTime" : 1525163446305,"intList" : null,"nodeName" : null
}
对象转为byte数组:[B@3327bd23
json字符串转为对象:XwjUser [id=1, message=Hello World, sendTime=Tue May 01 16:30:46 CST 2018, intList=null]
byte数组转为对象:XwjUser [id=1, message=Hello World, sendTime=Tue May 01 16:30:46 CST 2018, intList=null]

注意,对象转json字符串时,对象中的NodeName首字母是大写,转出来是小写

2、list集合与json字符串

@Testpublic void testList() throws JsonGenerationException, JsonMappingException, IOException {List<XwjUser> userList = new ArrayList<>();userList.add(new XwjUser(1, "aaa", new Date()));userList.add(new XwjUser(2, "bbb", new Date()));userList.add(new XwjUser(3, "ccc", new Date()));userList.add(new XwjUser(4, "ddd", new Date()));String jsonStr = mapper.writeValueAsString(userList);System.out.println("集合转为字符串:" + jsonStr);List<XwjUser> userListDes = mapper.readValue(jsonStr, List.class);System.out.println("字符串转集合:" + userListDes);}

运行结果:

集合转为字符串:[ {"id" : 1,"message" : "aaa","sendTime" : 1525164096846,"intList" : null,"nodeName" : null
}, {"id" : 2,"message" : "bbb","sendTime" : 1525164096846,"intList" : null,"nodeName" : null
}, {"id" : 3,"message" : "ccc","sendTime" : 1525164096846,"intList" : null,"nodeName" : null
}, {"id" : 4,"message" : "ddd","sendTime" : 1525164096846,"intList" : null,"nodeName" : null
} ]
字符串转集合:[{id=1, message=aaa, sendTime=1525164096846, intList=null, nodeName=null}, {id=2, message=bbb, sendTime=1525164096846, intList=null, nodeName=null}, {id=3, message=ccc, sendTime=1525164096846, intList=null, nodeName=null}, {id=4, message=ddd, sendTime=1525164096846, intList=null, nodeName=null}]

3、map与json字符串

@SuppressWarnings("unchecked")@Testpublic void testMap() {Map<String, Object> testMap = new HashMap<>();testMap.put("name", "merry");testMap.put("age", 30);testMap.put("date", new Date());testMap.put("user", new XwjUser(1, "Hello World", new Date()));try {String jsonStr = mapper.writeValueAsString(testMap);System.out.println("Map转为字符串:" + jsonStr);try {Map<String, Object> testMapDes = mapper.readValue(jsonStr, Map.class);System.out.println("字符串转Map:" + testMapDes);} catch (IOException e) {e.printStackTrace();}} catch (JsonProcessingException e) {e.printStackTrace();}}

运行结果:

Map转为字符串:{"date" : 1525164199804,"name" : "merry","user" : {"id" : 1,"message" : "Hello World","sendTime" : 1525164199805,"intList" : null,"nodeName" : null},"age" : 30
}
字符串转Map:{date=1525164199804, name=merry, user={id=1, message=Hello World, sendTime=1525164199805, intList=null, nodeName=null}, age=30}

4、修改转换时的日期格式:

@Testpublic void testOther() throws IOException {// 修改时间格式mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));XwjUser user = new XwjUser(1, "Hello World", new Date());user.setIntList(Arrays.asList(1, 2, 3));String jsonStr = mapper.writeValueAsString(user);System.out.println("对象转为字符串:" + jsonStr);}

运行结果:

对象转为字符串:{"id" : 1,"message" : "Hello World","sendTime" : "2018-05-01 16:44:06","intList" : [ 1, 2, 3 ],"nodeName" : null
}



原文链接:https://www.cnblogs.com/xuwenjin/p/8976696.html

这篇关于使用objectMapper处理数据之间的转化详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/826920

相关文章

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ

一文深入详解Python的secrets模块

《一文深入详解Python的secrets模块》在构建涉及用户身份认证、权限管理、加密通信等系统时,开发者最不能忽视的一个问题就是“安全性”,Python在3.6版本中引入了专门面向安全用途的secr... 目录引言一、背景与动机:为什么需要 secrets 模块?二、secrets 模块的核心功能1. 基

一文详解MySQL如何设置自动备份任务

《一文详解MySQL如何设置自动备份任务》设置自动备份任务可以确保你的数据库定期备份,防止数据丢失,下面我们就来详细介绍一下如何使用Bash脚本和Cron任务在Linux系统上设置MySQL数据库的自... 目录1. 编写备份脚本1.1 创建并编辑备份脚本1.2 给予脚本执行权限2. 设置 Cron 任务2

电脑提示xlstat4.dll丢失怎么修复? xlstat4.dll文件丢失处理办法

《电脑提示xlstat4.dll丢失怎么修复?xlstat4.dll文件丢失处理办法》长时间使用电脑,大家多少都会遇到类似dll文件丢失的情况,不过,解决这一问题其实并不复杂,下面我们就来看看xls... 在Windows操作系统中,xlstat4.dll是一个重要的动态链接库文件,通常用于支持各种应用程序

一文详解如何在idea中快速搭建一个Spring Boot项目

《一文详解如何在idea中快速搭建一个SpringBoot项目》IntelliJIDEA作为Java开发者的‌首选IDE‌,深度集成SpringBoot支持,可一键生成项目骨架、智能配置依赖,这篇文... 目录前言1、创建项目名称2、勾选需要的依赖3、在setting中检查maven4、编写数据源5、开启热

SQL Server修改数据库名及物理数据文件名操作步骤

《SQLServer修改数据库名及物理数据文件名操作步骤》在SQLServer中重命名数据库是一个常见的操作,但需要确保用户具有足够的权限来执行此操作,:本文主要介绍SQLServer修改数据... 目录一、背景介绍二、操作步骤2.1 设置为单用户模式(断开连接)2.2 修改数据库名称2.3 查找逻辑文件名

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

SQL Server数据库死锁处理超详细攻略

《SQLServer数据库死锁处理超详细攻略》SQLServer作为主流数据库管理系统,在高并发场景下可能面临死锁问题,影响系统性能和稳定性,这篇文章主要给大家介绍了关于SQLServer数据库死... 目录一、引言二、查询 Sqlserver 中造成死锁的 SPID三、用内置函数查询执行信息1. sp_w

HTML5 搜索框Search Box详解

《HTML5搜索框SearchBox详解》HTML5的搜索框是一个强大的工具,能够有效提升用户体验,通过结合自动补全功能和适当的样式,可以创建出既美观又实用的搜索界面,这篇文章给大家介绍HTML5... html5 搜索框(Search Box)详解搜索框是一个用于输入查询内容的控件,通常用于网站或应用程