使用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将PDF表格自动提取并写入Word文档表格

《使用Python将PDF表格自动提取并写入Word文档表格》在实际办公与数据处理场景中,PDF文件里的表格往往无法直接复制到Word中,本文将介绍如何使用Python从PDF文件中提取表格数据,并将... 目录引言1. 加载 PDF 文件并准备 Word 文档2. 提取 PDF 表格并创建 Word 表格

使用Python实现局域网远程监控电脑屏幕的方法

《使用Python实现局域网远程监控电脑屏幕的方法》文章介绍了两种使用Python在局域网内实现远程监控电脑屏幕的方法,方法一使用mss和socket,方法二使用PyAutoGUI和Flask,每种方... 目录方法一:使用mss和socket实现屏幕共享服务端(被监控端)客户端(监控端)方法二:使用PyA

Python使用Matplotlib和Seaborn绘制常用图表的技巧

《Python使用Matplotlib和Seaborn绘制常用图表的技巧》Python作为数据科学领域的明星语言,拥有强大且丰富的可视化库,其中最著名的莫过于Matplotlib和Seaborn,本篇... 目录1. 引言:数据可视化的力量2. 前置知识与环境准备2.1. 必备知识2.2. 安装所需库2.3

MySQL数据目录迁移的完整过程

《MySQL数据目录迁移的完整过程》文章详细介绍了将MySQL数据目录迁移到新硬盘的整个过程,包括新硬盘挂载、创建新的数据目录、迁移数据(推荐使用两遍rsync方案)、修改MySQL配置文件和重启验证... 目录1,新硬盘挂载(如果有的话)2,创建新的 mysql 数据目录3,迁移 MySQL 数据(推荐两

HTML5的input标签的`type`属性值详解和代码示例

《HTML5的input标签的`type`属性值详解和代码示例》HTML5的`input`标签提供了多种`type`属性值,用于创建不同类型的输入控件,满足用户输入的多样化需求,从文本输入、密码输入、... 目录一、引言二、文本类输入类型2.1 text2.2 password2.3 textarea(严格

Python数据验证神器Pydantic库的使用和实践中的避坑指南

《Python数据验证神器Pydantic库的使用和实践中的避坑指南》Pydantic是一个用于数据验证和设置的库,可以显著简化API接口开发,文章通过一个实际案例,展示了Pydantic如何在生产环... 目录1️⃣ 崩溃时刻:当你的API接口又双叒崩了!2️⃣ 神兵天降:3行代码解决验证难题3️⃣ 深度

Linux内核定时器使用及说明

《Linux内核定时器使用及说明》文章详细介绍了Linux内核定时器的特性、核心数据结构、时间相关转换函数以及操作API,通过示例展示了如何编写和使用定时器,包括按键消抖的应用... 目录1.linux内核定时器特征2.Linux内核定时器核心数据结构3.Linux内核时间相关转换函数4.Linux内核定时

C++ move 的作用详解及陷阱最佳实践

《C++move的作用详解及陷阱最佳实践》文章详细介绍了C++中的`std::move`函数的作用,包括为什么需要它、它的本质、典型使用场景、以及一些常见陷阱和最佳实践,感兴趣的朋友跟随小编一起看... 目录C++ move 的作用详解一、一句话总结二、为什么需要 move?C++98/03 的痛点⚡C++

Python+FFmpeg实现视频自动化处理的完整指南

《Python+FFmpeg实现视频自动化处理的完整指南》本文总结了一套在Python中使用subprocess.run调用FFmpeg进行视频自动化处理的解决方案,涵盖了跨平台硬件加速、中间素材处理... 目录一、 跨平台硬件加速:统一接口设计1. 核心映射逻辑2. python 实现代码二、 中间素材处

MySQL中between and的基本用法、范围查询示例详解

《MySQL中betweenand的基本用法、范围查询示例详解》BETWEENAND操作符在MySQL中用于选择在两个值之间的数据,包括边界值,它支持数值和日期类型,示例展示了如何使用BETWEEN... 目录一、between and语法二、使用示例2.1、betwphpeen and数值查询2.2、be