使用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删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与

深入理解Go语言中二维切片的使用

《深入理解Go语言中二维切片的使用》本文深入讲解了Go语言中二维切片的概念与应用,用于表示矩阵、表格等二维数据结构,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录引言二维切片的基本概念定义创建二维切片二维切片的操作访问元素修改元素遍历二维切片二维切片的动态调整追加行动态

MySQL中的LENGTH()函数用法详解与实例分析

《MySQL中的LENGTH()函数用法详解与实例分析》MySQLLENGTH()函数用于计算字符串的字节长度,区别于CHAR_LENGTH()的字符长度,适用于多字节字符集(如UTF-8)的数据验证... 目录1. LENGTH()函数的基本语法2. LENGTH()函数的返回值2.1 示例1:计算字符串

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

prometheus如何使用pushgateway监控网路丢包

《prometheus如何使用pushgateway监控网路丢包》:本文主要介绍prometheus如何使用pushgateway监控网路丢包问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录监控网路丢包脚本数据图表总结监控网路丢包脚本[root@gtcq-gt-monitor-prome

mybatis执行insert返回id实现详解

《mybatis执行insert返回id实现详解》MyBatis插入操作默认返回受影响行数,需通过useGeneratedKeys+keyProperty或selectKey获取主键ID,确保主键为自... 目录 两种方式获取自增 ID:1. ​​useGeneratedKeys+keyProperty(推

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

Linux系统性能检测命令详解

《Linux系统性能检测命令详解》本文介绍了Linux系统常用的监控命令(如top、vmstat、iostat、htop等)及其参数功能,涵盖进程状态、内存使用、磁盘I/O、系统负载等多维度资源监控,... 目录toppsuptimevmstatIOStatiotopslabtophtopdstatnmon