SpringBoot默认使用Jackson,它与ObjectMapper的前世今生JSON工具(格式化、JSONObject转对象)

article/2025/10/28 1:30:01

Jackson与ObjectMapper

1、Jackson可以轻松地将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象;

2、ObjectMapper类是Jackson库的主要类。它称为ObjectMapper的原因是因为它将JSON映射为Java对象(序列化),或将Java对象映射到JSON(序列化)。

ObjectMapper是线程安全的,应尽可能重用。=====> 统一配置

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;@Configuration
public class ObjectMapperConfig {@Bean@Primarypublic ObjectMapper objectMapper(){ObjectMapper mapper = new ObjectMapper(); // new 的过程比较耗时// 忽略json字符串中不识别的字段mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);// 其他需求,按需配置return mapper;}}

Jackson中的常用注解

@JsonIgnore 标注在字段上,序列化时忽略的字段

@JsonProperty 标注在字段上,序列化时按自定义的字段序列化

@JsonFormat 标注在时间类型(Date)字段上,序列化时按指定的日期格式序列化

@JsonInclude 标注在类上,序列化时按自定义的特性处理

@JsonIgnoreProperties 标注在类上,序列化时要忽略的类的属性字段,支持多个

@JsonSerialize

枚举类定义

package coupon;import lombok.AllArgsConstructor;
import lombok.Getter;@Getter
@AllArgsConstructor
public enum CouponEnum {USABLE("可用的", 0),USED("已使用", 1);private String desc;private Integer code;
}

类定义

package coupon;import com.fasterxml.jackson.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;import java.util.Date;@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@JsonInclude(JsonInclude.Include.NON_NULL)  // 不允许序列化的值为null
@JsonIgnoreProperties({"couponCode"})
public class Coupon {@JsonIgnoreprivate Long id;@JsonProperty("user_id")private Long userId;private String couponCode;@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy/MM/dd hh:mm:ss")private Date assignTime;private CouponEnum couponEnum;private CouponTemplate couponTemplate;@Data@AllArgsConstructor@NoArgsConstructor@Accessors(chain = true)public static class CouponTemplate{private String name;private String logo;}public static Coupon fake(){return new Coupon(1L, 100L, "Merchant_01", new Date(),CouponEnum.USED,new CouponTemplate("全品券", "All_used"));}
}

测试

pom里引入依赖

        <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
package com.insight.cloudeureka;import com.fasterxml.jackson.databind.ObjectMapper;
import coupon.Coupon;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;@SpringBootTest
@RunWith(SpringRunner.class)
@Slf4j
public class JsonAnnoTest {@Autowiredprivate ObjectMapper mapper;@Testpublic void testJacksonAnno() throws Exception{Coupon coupon = Coupon.fake();coupon.setCouponTemplate(null);// {"assignTime":"2021/07/18 05:11:20","couponEnum":"USED","user_id":100}log.info("ObjectMapper se Coupon: {}", mapper.writeValueAsString(coupon));}
}

ObjectMapper 反序列化用readValue方法 

测试结果 

 实现JsonSerializer<T>

package coupon;import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.text.SimpleDateFormat;public class CouponSerialize extends JsonSerializer<Coupon> {@Overridepublic void serialize(Coupon coupon, JsonGenerator generator, SerializerProvider serializerProvider) throws IOException {// 开始序列化generator.writeStartObject();generator.writeStringField("id", String.valueOf(coupon.getId()));generator.writeStringField("userId", coupon.getUserId().toString());generator.writeStringField("couponCode", coupon.getCouponCode());generator.writeStringField("assignTime", new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(coupon.getAssignTime()));generator.writeStringField("couponEnum",coupon.getCouponEnum().getDesc());generator.writeStringField("name", coupon.getCouponTemplate().getName());generator.writeStringField("logo", coupon.getCouponTemplate().getLogo());// 结束序列化generator.writeEndObject();}
}

 如果自己实现序列化,那么需要将类上的注解&字段上的JSON注解去掉

一个注解完成多个注解的功能。

不去掉类的相关JSON注解,会输出,与上对比可知,自己实现的接口,并没有起作用!

{"assignTime":"2021/07/18 06:53:29","couponEnum":"USED","couponTemplate":{"name":"全品券","logo":"All_used"},"user_id":100}

JSON工具(格式化、JSONObject转对象)

public class JsonUtil {public static <T> BaseRet<T> convert2BaseRet(String json, Class... classes) {ParameterizedTypeImpl beforeType = null;if (classes.length != 0) {//支持多级泛型的解析for (int i = classes.length - 1; i > 0; i--) {beforeType = new ParameterizedTypeImpl(new Type[]{beforeType == null ? classes[i] : beforeType},null, classes[i - 1]);}}return JSON.parseObject(json, beforeType);}public static String formatJson(String jsonStr) {if (null != jsonStr && !"".equals(jsonStr)) {StringBuilder sb = new StringBuilder();char current = 0;int indent = 0;for (int i = 0; i < jsonStr.length(); ++i) {char last = current;current = jsonStr.charAt(i);switch (current) {case ',':sb.append(current);if (last != '\\') {sb.append('\n');addIndentBlank(sb, indent);}break;case '[':case '{':sb.append(current);sb.append('\n');++indent;addIndentBlank(sb, indent);break;case ']':case '}':sb.append('\n');--indent;addIndentBlank(sb, indent);sb.append(current);break;default:sb.append(current);}}return sb.toString();} else {return "";}}private static void addIndentBlank(StringBuilder sb, int indent) {for (int i = 0; i < indent; ++i) {sb.append('\t');}}public static JSONObject toJSONObject(T t){return JSONObject.parseObject(JSON.toJSONString(t));}public static T toClass(JSONObject jsonObject,Class<T> claz){return JSONObject.parseObject(jsonObject.toJSONString(),claz);}}


http://chatgpt.dhexx.cn/article/ig38PRK3.shtml

相关文章

Json☀️ 二、使用 JsonUtility 创建并解析 Json

文章目录 &#x1f7e5; 要生成的 Json&#x1f7e7; 创建 Json 方法&#x1f7e8; 解析 Json 方法 在我们项目中&#xff0c;可能经常用到解析 Json&#xff0c; 但有时也需要存档的工作。那该怎样生成Json呢&#xff1f; 下面我们就以上节 Json 例子为例&#xff0c;来讲解如…

Jackson API指南(*)

一.Jackson 概述 与 依赖 1.市面上用于在 Java 中解析 Json 的第三方库&#xff0c;随便一搜不下几十种&#xff0c;其中的佼佼者有 Google 的 Gson&#xff0c; Alibaba 的 Fastjson以及本文的 jackson。 2.我们在学习一门技术之前&#xff0c;首选要了解这门技术的优劣性&am…

Jackson 工具类使用及配置指南

目录 前言Jackson使用工具类Jackson配置属性Jackson解析JSON数据Jackson序列化Java对象 前言 Json数据格式这两年发展的很快&#xff0c;其声称相对XML格式有很对好处&#xff1a; 容易阅读&#xff1b;解析速度快&#xff1b;占用空间更少。 不过&#xff0c;JSON 和 XML…

docker 命令(2) 容器数据持久化

1. docker ps 查看所有运行状态的容器. 2.docker ps -a 查看全部状态的容器列表。 3. docker rmi image名字 删除一个镜像。 4.容器持久化&#xff1a; 这样的话容器即使删了 但是数据依然在 主机的目录未指定的话 默认就会给你建一个 docker run --name mysql_pro -p 330…

jprofiler 连接 docker中的jvm

jprofiler 官网&#xff1a; Java Profiler - JProfiler 1: docker-compose 指定端口&#xff0c; docker 为 -p 指定端口 2&#xff1a;官网下载 liunx版本及windows版本&#xff1a; 我用的是12.0.4 windows本地 win10安装 liunx 版本 上传是liun服务器 3&#xff1a; 在…

Java中Jackson库操作json的基本操作

这段工作中总会遇到使用Java处理JSON的情况&#xff0c;大部分都使用的是开源工具Jackson实现的。因此总结一下发上来&#xff0c;希望对看到的人有所帮助。 上一篇文档中&#xff0c;我已经讲过Java如何使用Jackson来对Json进行序列化&#xff0c;这边我再稍微回顾一下。 Ja…

java操作k8s api示例:通过java完成对kubenetes原生资源对象(pod、node、namespace、servcie、deployment)和自定义资源对象CRD的增删改查或事件监听

本文目标 基于官方kubernetes-client/java类库&#xff0c;实现通过java完成对kubenetes原生资源对象&#xff08;pod、node、namespace、servcie、deployment&#xff09;和自定义资源对象&#xff08;如&#xff1a;cluster&#xff09;的增删改查或事件监听&#xff08;wat…

Jackson注解 @JsonCreator

当json在反序列化时&#xff0c;默认选择类的无参构造函数创建类对象&#xff0c;当没有无参构造函数时会报错&#xff0c;JsonCreator作用就是指定反序列化时用的无参构造函数。构造方法的参数前面需要加上JsonProperty,否则会报错。 JsonCreatorpublic Person(JsonProperty(&…

Spring中读取本地json文件,并交给Spring容器管理

我们经常在项目开发中遇到项目数据初始化的问题&#xff0c;例如一些超管&#xff0c;管理员账号&#xff1b;或者地图包&#xff0c;电话号码包&#xff0c;之类的东西。放到到一个json文件里面&#xff08;大的数据字典包可以放到搜索引擎里面&#xff0c;改情况本文不做讨论…

导入jackson-databind依赖后tomcat报错Cannot resolve com.fasterxml.jackson.core:jackson-databind

1》解决步骤&#xff1a; 项目启动前先打开tomcat里面的conf里面的catalina.properties文件夹 如&#xff1a;apache-tomcat-8.5.83\conf\catalina.properties 后面在里面找到如下&#xff1a;红线处 往下找到如下&#xff1a; 将上面的 红波浪线内容添加到后面&#xff1a…

通过Kettle工具解析Json接口数据并且保存到数据库中的详细操作

最近接到一个业务需求&#xff0c;要把一个Json接口数据获取下来并且保存到数据库中&#xff0c;考虑到应用代码实现功能需要耗费一定时间和精力&#xff0c;一旦需要修改&#xff0c;就得重启项目等。于是就选择利用Kettle工具来实现这个业务功能&#xff0c;将其从项目源码中…

树莓派安装wiringpi显示不存在解决方法

环境&#xff1a;树莓派4B 使用sudo apt-get install wiringpi 指令安装wiringpi包时&#xff0c;出现下面的提示&#xff1a; Reading package lists... Done Building dependency tree... Done Reading state information... Done Package wiringpi is not available, but …

[ARM+Linux] 基于wiringPi库的串口通信

wiringOP-master/examples/serialTest.c中&#xff0c;wiringPi库中自带的串口程序&#xff1a; #include <stdio.h> #include <string.h> #include <errno.h>#include <wiringPi.h> #include <wiringSerial.h>int main () {int fd ;int count …

树莓派 Raspberry Pi —— wiringPi库安装

树莓派的GPIO可以像单片机&#xff08;51单片机&#xff0c;Arduino&#xff0c;STM32等&#xff09;一样进行IO控制&#xff08;输出高、低电平&#xff0c;IIC&#xff0c;SPI&#xff0c;串口通信&#xff0c;PWM输出等&#xff09;&#xff0c;在此使用常用的WiringPi库来进…

树莓派 wiringPi 库

wiringPi是一个很棒的树莓派IO控制库&#xff0c;使用C语言开发&#xff0c;提供了丰富的接口&#xff1a;GPIO控制&#xff0c;中断&#xff0c;多线程&#xff0c;等等 检查树莓派是否已安装 wiringPi&#xff0c;在树莓派终端输入&#xff1a; gpio -v // 会在终端中输出…

树莓派安装wiringPi

在学习微雪的2-CH CAN FD HAT时&#xff0c;根据官网步骤在树莓派安装wiringPi sudo apt-get install wiringpi #对于树莓派4B可能需要进行升级&#xff1a; wget https://project-downloads.drogon.net/wiringpi-latest.deb&#xff08;此链接安装可能出错&#xff0c;如果出…

解决wiringPi库与64位树莓派之间不兼容的问题

目录 一.问题现象&#xff1a; 二.解决方案&#xff08;网站&#xff09;可以直接点这下载 一.问题现象&#xff1a; 今天在练习wiringPi库的使用时候&#xff0c;在最后编译的时候出现了这个问题 主要问题是这个skipping incompatible&#xff01; skipping incompatible. …

树莓派安装WiringPi以及找不到wiringPi.h文件解决方法(图文教程)

目录 安装WiringPi 失败的过程&#xff1a; 选择的方法&#xff1a; 安装步骤&#xff1a; 找不到wiringPi.h文件解决方法 失败过程&#xff1a; 解决方法&#xff1a; 安装WiringPi 失败的过程&#xff1a; 通过分别使用sudo apt-get install wiringPi 和 wget https…

树莓派的wiringPi库

一、wiringPi库 树莓派的外设开发都是基于wiringPi库&#xff0c;wiringPi是树莓派IO控制库&#xff0c;使用C语言开发&#xff0c;提供了丰富的接口&#xff1a;GPIO控制&#xff0c;中断&#xff0c;多线程&#xff0c;等等。 wiringPi库的安装 进入 wiringPi的github (htt…

玩转树莓派三、树莓派安装GPIO库接口wiringpi

WiringPi简介 WiringPi 是由 Gordon Henderson 使用 C 语言编写的一个基于 PIN接口的 GPIO 控制函数库&#xff0c;适用于所有Raspberry Pi 中使用的 BCM2835、BCM2836 和 BCM2837 SoC 设备&#xff0c;使用过 Arduino 控制板的开发人员应该会对此非常熟悉。 wiringPi 包括一…