当前位置: 首页 > news >正文

Jackson

first you need to add dependence:
gradle:

implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.1'
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.13.1'

原生Jackson的使用示例:

/*** 原生Jackson的使用示例*/
public class JacksonUsageDemo {public static void main(String[] args) throws JsonProcessingException {Address address1 = new Address("北京", "王府井12号", true);Address address2 = new Address("成都", "天府大道55号", false);Person person = new Person("张三", 18, Gender.MALE, Arrays.asList(address1, address2));ObjectMapper objectMapper = new ObjectMapper();String json = objectMapper.writeValueAsString(person);System.out.println(json);Person result = objectMapper.readValue(json, Person.class);System.out.println(result);}@Data@NoArgsConstructor@AllArgsConstructorprivate static class Person {private String name;private Integer age;private Gender gender;private List<Address> addressList;}@Data@NoArgsConstructor@AllArgsConstructorprivate static class Address {private String city;private String detail;private Boolean isPrimary;}private enum Gender {MALE, FEMALE;}
}

if JSON and JavaBean are not same

场景一:JSON比JavaBean多字段,在反序列化时忽略未知字段

使用@JsonIgnoreProperties:可以忽略指定字段,也可以忽略本类所有未知字段

  • @JsonIgnoreProperties(value = “year”):ignore the value of json
  • @JsonIgnoreProperties(ignoreUnknown = true):ignore every unknown value of JSON
  @Data@NoArgsConstructor@AllArgsConstructor@JsonIgnoreProperties(value = "year")
//  @JsonIgnoreProperties(ignoreUnknown = true)private static class Car {private String color;private String type;}

场景二:需要的JSON比JavaBean少字段,在序列化时忽略多余字段

  • 用@JsonIgnore在字段级别忽略
  • 用@JsonIgnoreType在类级别忽略
@RestController
public class FieldsLessController {@GetMapping("/teachers/{id}")public Teacher getStudentById(@PathVariable("id") String id) {return new Teacher(id, "刘老师", Gender.FEMALE);}@Data@NoArgsConstructor@AllArgsConstructorprivate static class Teacher {private String id;private String name;@JsonIgnoreprivate Gender gender;}//  @JsonIgnoreTypeprivate enum Gender {MALE, FEMALE;}
}

场景三:字段名不一致,在序列化和反序列化时改变字段名

  • 使用@JsonProperty
@RestController
public class FieldsNameMismatchController {@GetMapping("/articles/{id}")public Article getStudentById(@PathVariable("id") String id) {return new Article(id, "论持久战");}@Data@NoArgsConstructor@AllArgsConstructorprivate static class Article {@JsonProperty("articleId")private String id;@JsonProperty("articleTitle")private String title;}
}

json将会返回articleI&&articleTitle

场景四:结构不一致,在序列化时将对象拍平

  • 使用@JsonUnwrapped

拍平后:
{
“id”: “1”,
“firstName”: “John”,
“lastName”: “Doe”
}

@RestController
@Slf4j
public class StructureMismatchController {@PostMapping("/employees")public void createEmployee(@RequestBody Employee employee) {log.info("create employee: {}", employee);}@GetMapping("/employees/{id}")public Employee getStudentById(@PathVariable("id") String id) {return new Employee(id, new Name("John", "Doe"));}@Data@NoArgsConstructor@AllArgsConstructorprivate static class Employee {private String id;@JsonUnwrappedprivate Name name;}@Data@NoArgsConstructor@AllArgsConstructorprivate static class Name {private String firstName;private String lastName;}
}

场景五:JSON中的枚举是数字形式,在序列化时使用枚举的序数值

  • 使用@JsonValue
@RestController
public class EnumOrdinalController {@GetMapping("/users/v1/{id}")public User getUserById(@PathVariable String id) {return new User(id, "小红", Gender.FEMALE);}@Data@NoArgsConstructor@AllArgsConstructorprivate static class User {private String id;private String name;private Gender gender;}private static enum Gender {MALE, FEMALE;@JsonValuepublic int getOrdinal() {return ordinal();}}
}

场景六:JSON中的时间是特定格式,在序列化时指定时间格式

  • 使用@JsonFormat
@RestController
public class TimeFormatController {@GetMapping("/events/{id}")public Event getEvent(@PathVariable("id") String id) {return new Event(id, "pay", new Date());}@Data@NoArgsConstructor@AllArgsConstructorprivate static class Event {private String id;private String name;@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")private Date time;}
} 

使用自定义序列化器,枚举序列化成数字

@JsonSerialize(using = GenderSerializer.class)

@RestController
public class CustomSerializationController {@GetMapping("/users/v2/{id}")public User getUserById(@PathVariable String id) {return new User(id, "小红", Gender.FEMALE);}@Data@NoArgsConstructor@AllArgsConstructorprivate static class User {private String id;private String name;@JsonSerialize(using = GenderSerializer.class)private Gender gender;}private static enum Gender {MALE, FEMALE;}private static class GenderSerializer extends StdSerializer<Gender> {protected GenderSerializer() {super(Gender.class);}@Overridepublic void serialize(Gender value, JsonGenerator gen, SerializerProvider provider)throws IOException {gen.writeNumber(value.ordinal());}}
}

相关文章:

Jackson

first you need to add dependence: gradle: implementation com.fasterxml.jackson.core:jackson-databind:2.13.1 implementation com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.13.1原生Jackson的使用示例: /*** 原生Jackson的使用示例*/ public class Jacks…...

字节软件测试岗:惨不忍睹的三面,幸好做足了准备,月薪19k,已拿offer

我今年25岁&#xff0c;专业是电子信息工程本科&#xff0c;19年年末的时候去面试&#xff0c;统一投了测试的岗位&#xff0c;软件硬件都有&#xff0c;那时候面试的两家公司都是做培训的&#xff0c;当初没啥钱&#xff0c;他们以面试为谎言再推荐去培训这点让我特别难受。后…...

vue使用axios发送post请求携带json body参数,后端使用@RequestBody进行接收

前言 最近在做自己项目中&#xff0c;做一个非常简单的新增用户场景&#xff0c;但是使用原生axios发送post请求的时候&#xff0c;还是踩了不少坑的。 唉&#xff0c;说多了都是泪&#xff0c;小小一个新增业务&#xff0c;在自己前后端一起开发的时候&#xff0c;硬是搞了好…...

【python百炼成魔】python之列表详解

文章目录一. 列表的概念1.1 列表是什么&#xff1f;1.2 为什么要使用列表&#xff1f;1.3 列表的定义二. 列表的增删改查操作2.1 列表的读取2.2 列表的切片2.3 列表的查询操作2.3.1 not in ,in 表达式2.3.2 列表元素遍历2.4 列表元素的增加操作2.4.1 append()的相关用法2.4.2 e…...

如何学习 Web3

在本文中&#xff0c;我将总结您可以采取的步骤来学习 Web3。从哪儿开始&#xff1f;当我们想要开始新事物时&#xff0c;我们需要一些指导&#xff0c;以免在一开始就卡住。但我们都是不同的&#xff0c;我们有不同的学习方式。这篇文章基于我学习 Web3 的非常个人的经验。路线…...

大数据框架之Hadoop:MapReduce(一)MapReduce概述

1.1MapReduce定义 MapReduce是一个分布式计算框架&#xff0c;用于编写批处理应用程序&#xff0c;是用户开发“基于Hadoop的数据分析应用”的核心框架。 MapReduce核心功能是将用户编写的业务逻辑代码和自带默认组件整合成一个完整的分布式运算程序&#xff0c;并发运行在一…...

一文搞定python语法进阶

前言前面我们已经学习了Python的基础语法&#xff0c;了解了Python的分支结构&#xff0c;也就是选择结构、循环结构以及函数这些具体的框架&#xff0c;还学习了列表、元组、字典、字符串这些Python中特有的数据结构&#xff0c;还用这些语法完成了一个简单的名片管理系统。下…...

2019蓝桥杯真题数列求值(填空题) C语言/C++

题目描述 本题为填空题&#xff0c;只需要算出结果后&#xff0c;在代码中使用输出语句将所填结果输出即可。 给定数列 1,1,1,3,5,9,17,⋯&#xff0c;从第 4 项开始&#xff0c;每项都是前 3 项的和。 求第 20190324 项的最后 4 位数字。 运行限制 最大运行时间&#xff1a…...

spring中@Autowire和@Resource的区别在哪里?

介绍今天使用Idea写代码的时候&#xff0c;看到之前的项目中显示有warning的提示&#xff0c;去看了下&#xff0c;是如下代码?Autowire private JdbcTemplate jdbcTemplate;提示的警告信息Field injection is not recommended Inspection info: Spring Team recommends: &quo…...

算法训练营DAY54|583. 两个字符串的删除操作、72. 编辑距离

583. 两个字符串的删除操作 - 力扣&#xff08;LeetCode&#xff09;https://leetcode.cn/problems/delete-operation-for-two-strings/这道题也是对于编辑距离的铺垫题目&#xff0c;是可以操作两个字符串的删除&#xff0c;使得两个字符串的字符完全相同&#xff0c;这道题可…...

【Ctfshow_Web】信息收集和爆破

0x00 信息收集 web1 直接查看源码 web2 查看不了源码&#xff0c;抓包即可看到&#xff08;JS拦截了F12&#xff09; web3 抓包&#xff0c;发送repeater&#xff0c;在响应包中有Flag字段 web4 题目提示后台地址在robots&#xff0c;访问/robots.txt看到Disallow: /fl…...

基于机器学习的推荐算法研究与实现

摘要随着互联网的普及&#xff0c;人们可以通过搜索引擎、社交网络等方式获取大量的信息资源。但是&#xff0c;面对如此之多的信息&#xff0c;人们往往会感到迷失和困惑&#xff0c;无法快速准确地找到自己需要的信息。在这种情况下&#xff0c;推荐算法的出现为我们提供了一…...

(二十四)ATP应用测试平台——springboot集成fastdfs上传与下载功能

前言 本节内容我们主要介绍一下如何在springboot项目中集成fastdfs组件&#xff0c;实现文件的上传与下载。关于fastdfs服务中间键的安装过程&#xff0c;本节内容不做介绍。fastdfs是一个轻量级的分布式文件系统&#xff0c;也是我们文件存储中常常使用的组件之一&#xff0c…...

linux好用命令+vs快捷键

linux好用命令 功能指令跳转到vim界面的最后一行shift键g复制当前路径下所有文件和目录&#xff08;加-r才行&#xff09;到target目录cp -r * /home/target删除指定文件rm -rf test.txt文件重命名&#xff08;-i交互式提示&#xff09;mv -i file1 file2移动某个内容&#xf…...

Git 构建分布式版本控制系统

版本控制概念Gitlab部署1.版本控制概念 1.1分类 &#xff08;一&#xff09;1 本地版本控制系统&#xff08;传统模式&#xff09; &#xff08;二&#xff09;2 集中化的版本控制系统 CVS、Subversion&#xff08;SVN&#xff09; &#xff08;三&#xff09;3 分布式…...

Day891.一主多从的切换正确性 -MySQL实战

一主多从的切换正确性 Hi&#xff0c;我是阿昌&#xff0c;今天学习记录的是关于一主多从的切换正确性的内容。 在切换任务的时候&#xff0c;要先主动跳过这些错误&#xff0c;通过主动跳过一个事务或者直接设置跳过指定的错误&#xff0c;用GTID解决找同步位点的问题 大多…...

【论文笔记】图像修复Learning Joint Spatial-Temporal Transformations for Video Inpainting

论文地址&#xff1a;https://arxiv.org/abs/2007.10247 源码地址&#xff1a;GitHub - researchmm/STTN: [ECCV2020] STTN: Learning Joint Spatial-Temporal Transformations for Video Inpainting 一、项目介绍 当下SITA的方法大多采用注意模型&#xff0c;通过搜索参考帧…...

代码随想录算法训练营第二天 | 977.有序数组的平方 、209.长度最小的子数组 、59.螺旋矩阵II、总结

打卡第二天&#xff0c;认真做了两道题目&#xff0c;顶不住了好困&#xff0c;明天早上练完车回来再重新看看。 今日任务 第一章数组 977.有序数组的平方209.长度最小的子数组59.螺旋矩阵II 977.有序数组的平方 给你一个按 非递减顺序 排序的整数数组 nums&#xff0c;返回 每…...

Python pickle模块:实现Python对象的持久化存储

Python 中有个序列化过程叫作 pickle&#xff0c;它能够实现任意对象与文本之间的相互转化&#xff0c;也可以实现任意对象与二进制之间的相互转化。也就是说&#xff0c;pickle 可以实现 Python 对象的存储及恢复。值得一提的是&#xff0c;pickle 是 python 语言的一个标准模…...

【C++】C/C++内存管理

文章目录1. C/C内存分布2. C语言当中的动态内存管理3. C 内存管理方式3.1 new/delete操作内置类型3.2 new和delete操作自定义类型4. operator new 和operator delete 函数5. new和delete的实现原理5.1 内置类型5.2 自定义类型6. 定位new表达式(placement-new)7. 常见面试题7.1 …...

python打卡day49

知识点回顾&#xff1a; 通道注意力模块复习空间注意力模块CBAM的定义 作业&#xff1a;尝试对今天的模型检查参数数目&#xff0c;并用tensorboard查看训练过程 import torch import torch.nn as nn# 定义通道注意力 class ChannelAttention(nn.Module):def __init__(self,…...

在鸿蒙HarmonyOS 5中使用DevEco Studio实现录音机应用

1. 项目配置与权限设置 1.1 配置module.json5 {"module": {"requestPermissions": [{"name": "ohos.permission.MICROPHONE","reason": "录音需要麦克风权限"},{"name": "ohos.permission.WRITE…...

Hive 存储格式深度解析:从 TextFile 到 ORC,如何选对数据存储方案?

在大数据处理领域&#xff0c;Hive 作为 Hadoop 生态中重要的数据仓库工具&#xff0c;其存储格式的选择直接影响数据存储成本、查询效率和计算资源消耗。面对 TextFile、SequenceFile、Parquet、RCFile、ORC 等多种存储格式&#xff0c;很多开发者常常陷入选择困境。本文将从底…...

JavaScript基础-API 和 Web API

在学习JavaScript的过程中&#xff0c;理解API&#xff08;应用程序接口&#xff09;和Web API的概念及其应用是非常重要的。这些工具极大地扩展了JavaScript的功能&#xff0c;使得开发者能够创建出功能丰富、交互性强的Web应用程序。本文将深入探讨JavaScript中的API与Web AP…...

4. TypeScript 类型推断与类型组合

一、类型推断 (一) 什么是类型推断 TypeScript 的类型推断会根据变量、函数返回值、对象和数组的赋值和使用方式&#xff0c;自动确定它们的类型。 这一特性减少了显式类型注解的需要&#xff0c;在保持类型安全的同时简化了代码。通过分析上下文和初始值&#xff0c;TypeSc…...

python爬虫——气象数据爬取

一、导入库与全局配置 python 运行 import json import datetime import time import requests from sqlalchemy import create_engine import csv import pandas as pd作用&#xff1a; 引入数据解析、网络请求、时间处理、数据库操作等所需库。requests&#xff1a;发送 …...

【安全篇】金刚不坏之身:整合 Spring Security + JWT 实现无状态认证与授权

摘要 本文是《Spring Boot 实战派》系列的第四篇。我们将直面所有 Web 应用都无法回避的核心问题&#xff1a;安全。文章将详细阐述认证&#xff08;Authentication) 与授权&#xff08;Authorization的核心概念&#xff0c;对比传统 Session-Cookie 与现代 JWT&#xff08;JS…...

算法—栈系列

一&#xff1a;删除字符串中的所有相邻重复项 class Solution { public:string removeDuplicates(string s) {stack<char> st;for(int i 0; i < s.size(); i){char target s[i];if(!st.empty() && target st.top())st.pop();elsest.push(s[i]);}string ret…...

C# WPF 左右布局实现学习笔记(1)

开发流程视频&#xff1a; https://www.youtube.com/watch?vCkHyDYeImjY&ab_channelC%23DesignPro Git源码&#xff1a; GitHub - CSharpDesignPro/Page-Navigation-using-MVVM: WPF - Page Navigation using MVVM 1. 新建工程 新建WPF应用&#xff08;.NET Framework) 2.…...

数据挖掘是什么?数据挖掘技术有哪些?

目录 一、数据挖掘是什么 二、常见的数据挖掘技术 1. 关联规则挖掘 2. 分类算法 3. 聚类分析 4. 回归分析 三、数据挖掘的应用领域 1. 商业领域 2. 医疗领域 3. 金融领域 4. 其他领域 四、数据挖掘面临的挑战和未来趋势 1. 面临的挑战 2. 未来趋势 五、总结 数据…...