使用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

相关文章

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

PHP轻松处理千万行数据的方法详解

《PHP轻松处理千万行数据的方法详解》说到处理大数据集,PHP通常不是第一个想到的语言,但如果你曾经需要处理数百万行数据而不让服务器崩溃或内存耗尽,你就会知道PHP用对了工具有多强大,下面小编就... 目录问题的本质php 中的数据流处理:为什么必不可少生成器:内存高效的迭代方式流量控制:避免系统过载一次性

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。

MySQL的JDBC编程详解

《MySQL的JDBC编程详解》:本文主要介绍MySQL的JDBC编程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录前言一、前置知识1. 引入依赖2. 认识 url二、JDBC 操作流程1. JDBC 的写操作2. JDBC 的读操作总结前言本文介绍了mysq

Redis 的 SUBSCRIBE命令详解

《Redis的SUBSCRIBE命令详解》Redis的SUBSCRIBE命令用于订阅一个或多个频道,以便接收发送到这些频道的消息,本文给大家介绍Redis的SUBSCRIBE命令,感兴趣的朋友跟随... 目录基本语法工作原理示例消息格式相关命令python 示例Redis 的 SUBSCRIBE 命令用于订

Java使用Javassist动态生成HelloWorld类

《Java使用Javassist动态生成HelloWorld类》Javassist是一个非常强大的字节码操作和定义库,它允许开发者在运行时创建新的类或者修改现有的类,本文将简单介绍如何使用Javass... 目录1. Javassist简介2. 环境准备3. 动态生成HelloWorld类3.1 创建CtC

使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解

《使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解》本文详细介绍了如何使用Python通过ncmdump工具批量将.ncm音频转换为.mp3的步骤,包括安装、配置ffmpeg环... 目录1. 前言2. 安装 ncmdump3. 实现 .ncm 转 .mp34. 执行过程5. 执行结