河北秦皇岛建设局网站,科技素材,深圳十大装饰公司名单,seo排名培训公司陈老老老板#x1f9b8;#x1f468;#x1f4bb;本文专栏#xff1a;SpringBoot篇#xff08;主要讲一些与springboot整合相关的内容#xff09;#x1f468;#x1f4bb;本文简述#xff1a;本文讲一下Jackson常见用法#xff0c;超级详细。#x1f468; 本文专栏SpringBoot篇主要讲一些与springboot整合相关的内容 本文简述本文讲一下Jackson常见用法超级详细。 上一篇文章《SpringBoot篇》25.SpringBoot整合ActiveMQ 有任何问题都可以私聊我我能帮得上的一定帮忙感谢大佬们支持。 我认为人人都可以学好编程我愿意成为你的领路人需内推私聊 一、Jackson简介
说明本篇讲的是Jackson的详细用法Jackson工具类在文章最后直接复制粘贴即可使用。 Jackson是公司中必用的组件之一常用的还用阿里的Fastjson但是由于一些原因bug与漏洞是在是太多在注重安全的公司直接被pass还有就是谷歌的Gson这个没用过不太了解。 Spring MVC 的默认 json 解析器便是 Jackson。 Jackson 优点很多。 Jackson 所依赖的 jar 包较少 简单易用。与其他 Java 的 json 的框架 Gson 等相比 Jackson 解析大的 json 文件速度比较快Jackson 运行时占用内存比较低性能比较好Jackson 有灵活的 API可以很容易进行扩展和定制。
额外了解 Jackson 的 1.x 版本的包名是 org.codehaus.jackson 当升级到 2.x 版本时包名变为com.fasterxml.jackson。
Jackson 有三个核心包分别是 Streaming、Databid、Annotations通过这些包可以方便的对 JSON 进行操作.
jackson-core核心包提供基于流模式解析的相关 API它包括 JsonPaser 和 JsonGenerator。 Jackson 内部实现正是通过高性能的流模式 API 的 JsonGenerator 和 JsonParser 来生成和解析 json。jackson-annotations:注解包提供标准注解功能.jackson-databind :数据绑定包 提供基于对象绑定 解析的相关 API ObjectMapper 和树模型 解析的相关 API JsonNode基于对象绑定 解析的 API 和树模型解析的 API 依赖基于流模式解析的 API。包含上面两个包只导入这个坐标即可。
运行环境
idea2020.2jdk1.8springboot 2.7.9
下载demo直接去我的资源下载即可Jackson实例-附工具类
二、Json简介
说明 作为Java开发一定要学习Json在现在的前后端分离的项目中Json是最常见的数据交换格式。比如SpringBoot中RequestBody注解就是作为接收Json格式的注解在使用Postman进行测试时传输的raw-json也是Json格式数据。
JSON表示结构 对象数组: 对象结构以”{”大括号开始以”}”大括号结束,中间部分由0或多个以””分隔的”key(关键字)/value(值)”对构成关键字和值之间以””分隔语法结构如代码。这里给一个示例。
{array: [1,2,3],boolean: true,name: cllb,null: null,age: 12345,object: {height: 100,color: 红色},string: 陈老老老板
}三、springboot整合Jackson
1.创建项目
说明 创建一个空springboot项目2.7.9版本。这里就不过多复述了创建时将lombok组件选上十分方便无需再写Get/Set方法。 注意可以看到导入databind包会自动导入剩下两个包。
2.导入坐标
说明 可以看到导入databind包会自动导入剩下两个包。
dependencygroupIdcom.fasterxml.jackson.core/groupIdartifactIdjackson-databind/artifactIdversion2.13.3/version
/dependency3.配置文件
a.配置文件配置
properties格式
#指定日期格式比如yyyy-MM-dd HH:mm:ss或者具体的格式化类的全限定名
spring.jackson.date-format
#指定日期格式化时区比如America/Los_Angeles或者GMT10.
spring.jackson.time-zone
#是否开启Jackson的反序列化
spring.jackson.deserialization
#是否开启json的generators.
spring.jackson.generator
#指定Joda date/time的格式比如yyyy-MM-ddHH:mm:ss). 如果没有配置的话dateformat会作为backup
spring.jackson.joda-date-time-format
#指定json使用的Locale.
spring.jackson.locale
#是否开启Jackson通用的特性.
spring.jackson.mapper
#是否开启jackson的parser特性.
spring.jackson.parser
#指定PropertyNamingStrategy(CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES)或者指定PropertyNamingStrategy子类的全限定类名.
spring.jackson.property-naming-strategy
#是否开启jackson的序列化.
spring.jackson.serialization
#指定序列化时属性的inclusion方式具体查看JsonInclude.Include枚举.
spring.jackson.serialization-inclusionyml格式
spring:jackson:#日期格式化date-format: yyyy-MM-dd HH:mm:sstime-zone: GMT8#设置空如何序列化default-property-inclusion: non_null serialization:#格式化输出 indent_output: true#忽略无法转换的对象fail_on_empty_beans: falsedeserialization:#允许对象忽略json中不存在的属性fail_on_unknown_properties: falseparser:#允许出现特殊字符和转义符allow_unquoted_control_chars: true#允许出现单引号allow_single_quotes: true
b.自定义配置
说明 这里直接将Jackson工具类给大家自定义配置指的就是工具类中对于object_mapper的set赋值。什么方法都有演示也直接使用工具类进行。
package com.clllb.jackson.utils;import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;Slf4j
public class JacksonUtil {private static final ObjectMapper OBJECT_MAPPER new ObjectMapper();private static final ObjectMapper OBJECT_MAPPER_SNAKE_CASE new ObjectMapper();// 日期格式化private static final String STANDARD_FORMAT yyyy-MM-dd HH:mm:ss;static {//对象的所有字段全部列入OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.ALWAYS);//取消默认转换timestamps形式OBJECT_MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);//忽略空Bean转json的错误OBJECT_MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);//所有的日期格式都统一为以下的样式即yyyy-MM-dd HH:mm:ssOBJECT_MAPPER.setDateFormat(new SimpleDateFormat(STANDARD_FORMAT));//忽略 在json字符串中存在但是在java对象中不存在对应属性的情况。防止错误OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);}static {//对象的所有字段全部列入OBJECT_MAPPER_SNAKE_CASE.setSerializationInclusion(JsonInclude.Include.ALWAYS);//取消默认转换timestamps形式OBJECT_MAPPER_SNAKE_CASE.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);//忽略空Bean转json的错误OBJECT_MAPPER_SNAKE_CASE.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);//所有的日期格式都统一为以下的样式即yyyy-MM-dd HH:mm:ssOBJECT_MAPPER_SNAKE_CASE.setDateFormat(new SimpleDateFormat(STANDARD_FORMAT));//忽略 在json字符串中存在但是在java对象中不存在对应属性的情况。防止错误OBJECT_MAPPER_SNAKE_CASE.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);//转换为下划线OBJECT_MAPPER_SNAKE_CASE.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);}private JacksonUtil() {}/*** 对象转Json格式字符串** param obj 对象* return Json格式字符串*/public static T String obj2String(T obj) {if (obj null) {return null;}try {return obj instanceof String ? (String) obj : OBJECT_MAPPER.writeValueAsString(obj);} catch (JsonProcessingException e) {log.warn(Parse Object to String error : {}, e.getMessage());return null;}}/*** 对象转file* param fileName* param obj*/public static void obj2File(String fileName,Object obj){if (obj null){return;}try {OBJECT_MAPPER.writeValue(new File(fileName),obj);} catch (IOException e) {e.printStackTrace();}}/*** 对象转Json格式字符串; 属性名从驼峰改为下划线形式** param obj 对象* return Json格式字符串*/public static T String obj2StringFieldSnakeCase(T obj) {if (obj null) {return null;}try {ObjectMapper objectMapper OBJECT_MAPPER_SNAKE_CASE;return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);} catch (JsonProcessingException e) {log.warn(Parse Object to String error : {}, e.getMessage());return null;}}/*** 字符串转换为自定义对象 属性名从下划线形式改为驼峰** param str 要转换的字符串* param clazz 自定义对象的class对象* return 自定义对象*/public static T T string2ObjFieldLowerCamelCase(String str, ClassT clazz) {if (StringUtils.isEmpty(str) || clazz null) {return null;}try {ObjectMapper objectMapper OBJECT_MAPPER_SNAKE_CASE;return clazz.equals(String.class) ? (T) str : objectMapper.readValue(str, clazz);} catch (Exception e) {log.warn(Parse String to Object error : {}, e.getMessage());return null;}}/*** 字符串转换为自定义对象(List) 属性名从下划线形式改为驼峰** param str 要转换的字符串* param typeReference 自定义对象的typeReference List 对象* return 自定义对象*/public static T ListT string2ListFieldLowerCamelCase(String str, TypeReferenceListT typeReference) {if (StringUtils.isEmpty(str) || typeReference null) {return null;}try {ObjectMapper objectMapper OBJECT_MAPPER_SNAKE_CASE;return objectMapper.readValue(str, typeReference);} catch (Exception e) {log.warn(Parse String to Object error : {}, e.getMessage());return null;}}/*** 对象转Json格式字符串(格式化的Json字符串)** param obj 对象* return 美化的Json格式字符串*/public static T String obj2StringPretty(T obj) {if (obj null) {return null;}try {return obj instanceof String ? (String) obj : OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(obj);} catch (JsonProcessingException e) {log.warn(Parse Object to String error : {}, e.getMessage());return null;}}/*** 字符串转换为自定义对象** param str 要转换的字符串* param clazz 自定义对象的class对象* return 自定义对象*/public static T T string2Obj(String str, ClassT clazz) {if (StringUtils.isEmpty(str) || clazz null) {return null;}try {return clazz.equals(String.class) ? (T) str : OBJECT_MAPPER.readValue(str, clazz);} catch (Exception e) {log.warn(Parse String to Object error : {}, e.getMessage());return null;}}/*** 字符串转换为自定义字段转为list* param str* param typeReference* param T* return*/public static T T string2Obj(String str, TypeReferenceT typeReference) {if (StringUtils.isEmpty(str) || typeReference null) {return null;}try {return (T) (typeReference.getType().equals(String.class) ? str : OBJECT_MAPPER.readValue(str, typeReference));} catch (IOException e) {log.warn(Parse String to Object error, e);return null;}}public static T T string2Obj(String str, Class? collectionClazz, Class?... elementClazzes) {JavaType javaType OBJECT_MAPPER.getTypeFactory().constructParametricType(collectionClazz, elementClazzes);try {return OBJECT_MAPPER.readValue(str, javaType);} catch (IOException e) {log.warn(Parse String to Object error : {} e.getMessage());return null;}}
}
4.实体类
说明 这里创建一个user实体类
package com.clllb.jackson.PO;import lombok.Data;import java.util.List;Data
public class User {private String username;private Integer age;private ListString info;private Long userId;
}
项目样图
5.测试类
说明 测试类中直接调工具类中的方法非常简单附输出结果。
a.object类型转Json
说明 使用writeValueAsString方法 Testvoid obj2string(){User user new User();user.setUsername(clllb);user.setAge(24);user.setUserId(1L);ListString infoList new ArrayList();infoList.add(有一百万);infoList.add(发大财);user.setInfo(infoList);String json JacksonUtil.obj2String(user);System.out.println(json);}输出结果
{username:clllb,age:24,info:[有一百万,发大财],userId:1}b.object类型转file
说明 使用writeValue方法 Testvoid obj2file(){User user new User();user.setUsername(clllb);user.setAge(24);user.setUserId(1L);ListString infoList new ArrayList();infoList.add(有一百万);infoList.add(发大财);user.setInfo(infoList);String fileName ccccc;JacksonUtil.obj2File(fileName,user);}输出结果
c.string类型转Object自定义类型
说明 使用readValue方法 Testvoid string2obj(){String json {\username\:\clllb\,\age\:24,\info\:[\有一百万\,\发大财\],\userId\:11};User user JacksonUtil.string2Obj(json, User.class);System.out.println(user);}输出结果
User(usernameclllb, age24, info[有一百万, 发大财], userId11)d.string类型转Object自定义类型list
说明 使用readValue方法,传参变为TypeReference typeReference这里工具类用的重载方法名是相同的。
Testvoid string2objList(){String json [{\username\:\clllb\,\age\:24,\info\:[\有一百万\,\发大财\],\userId\:11},\n {\username\:\陈老老老板\,\age\:25,\info\:[\有一千万\,\发大大财\],\userId\:12}];ListUser user JacksonUtil.string2Obj(json, new TypeReferenceListUser(){});user.forEach(System.out::println);}输出结果
User(usernameclllb, age24, info[有一百万, 发大财], userId11)
User(username陈老老老板, age25, info[有一千万, 发大大财], userId12)e.object类型转String(驼峰转下划线)
说明 使用writeValueAsString方法,这里区别看工具类就会发现就是多了一个设置OBJECT_MAPPER_SNAKE_CASE.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE); Testvoid obj2sringSnakeCase(){User user new User();user.setUsername(clllb);user.setAge(24);user.setUserId(11L);ListString infoList new ArrayList();infoList.add(有一百万);infoList.add(发大财);user.setInfo(infoList);String json JacksonUtil.obj2StringFieldSnakeCase(user);System.out.println(json);}输出结果
{username:clllb,age:24,info:[有一百万,发大财],user_id:11}f.string类型下划线转Object类型
font color redb说明/font 使用readValue方法
javaTestvoid string2obj(){String json {\username\:\clllb\,\age\:24,\info\:[\有一百万\,\发大财\],\user_id\:11};User user JacksonUtil.string2Obj(json, User.class);System.out.println(user);}输出结果
User(usernameclllb, age24, info[有一百万, 发大财], userId11)g.string类型(下划线)转Object自定义类型list
说明 使用readValue方法,传参变为TypeReference typeReference这里工具类用的重载方法名是相同的。 Testvoid string2objSnakeCase(){String json [{\username\:\clllb\,\age\:24,\info\:[\有一百万\,\发大财\],\user_id\:11},\n {\username\:\陈老老老板\,\age\:25,\info\:[\有一千万\,\发大大财\],\user_id\:12}];ListUser user JacksonUtil.string2ListFieldLowerCamelCase(json, new TypeReferenceListUser(){});user.forEach(System.out::println);}输出结果
User(usernameclllb, age24, info[有一百万, 发大财], userId11)
User(username陈老老老板, age25, info[有一千万, 发大大财], userId12)总结工具类非常好用包含日常所需。Jackson常见用法总结。希望对您有帮助感谢阅读 结束语裸体一旦成为艺术便是最圣洁的。道德一旦沦为虚伪便是最下流的。 勇敢去做你认为正确的事不要被世俗的流言蜚语所困扰。
文章转载自: http://www.morning.tzmjc.cn.gov.cn.tzmjc.cn http://www.morning.ksgjy.cn.gov.cn.ksgjy.cn http://www.morning.bysey.com.gov.cn.bysey.com http://www.morning.rmxwm.cn.gov.cn.rmxwm.cn http://www.morning.qlrtd.cn.gov.cn.qlrtd.cn http://www.morning.rnpnn.cn.gov.cn.rnpnn.cn http://www.morning.kmldm.cn.gov.cn.kmldm.cn http://www.morning.rnygs.cn.gov.cn.rnygs.cn http://www.morning.ahlart.com.gov.cn.ahlart.com http://www.morning.zylrk.cn.gov.cn.zylrk.cn http://www.morning.lwgsk.cn.gov.cn.lwgsk.cn http://www.morning.gwsll.cn.gov.cn.gwsll.cn http://www.morning.ohmyjiu.com.gov.cn.ohmyjiu.com http://www.morning.jfgmx.cn.gov.cn.jfgmx.cn http://www.morning.fdwlg.cn.gov.cn.fdwlg.cn http://www.morning.xflwq.cn.gov.cn.xflwq.cn http://www.morning.jprrh.cn.gov.cn.jprrh.cn http://www.morning.hprmg.cn.gov.cn.hprmg.cn http://www.morning.jhkzl.cn.gov.cn.jhkzl.cn http://www.morning.znqztgc.cn.gov.cn.znqztgc.cn http://www.morning.jxjrm.cn.gov.cn.jxjrm.cn http://www.morning.xlmpj.cn.gov.cn.xlmpj.cn http://www.morning.zrqs.cn.gov.cn.zrqs.cn http://www.morning.hxftm.cn.gov.cn.hxftm.cn http://www.morning.mbrbg.cn.gov.cn.mbrbg.cn http://www.morning.bwjws.cn.gov.cn.bwjws.cn http://www.morning.yhwyh.cn.gov.cn.yhwyh.cn http://www.morning.nmhpq.cn.gov.cn.nmhpq.cn http://www.morning.jnrry.cn.gov.cn.jnrry.cn http://www.morning.dfygx.cn.gov.cn.dfygx.cn http://www.morning.jxpwr.cn.gov.cn.jxpwr.cn http://www.morning.ccpnz.cn.gov.cn.ccpnz.cn http://www.morning.rsnd.cn.gov.cn.rsnd.cn http://www.morning.mknxd.cn.gov.cn.mknxd.cn http://www.morning.jsrnf.cn.gov.cn.jsrnf.cn http://www.morning.phnbd.cn.gov.cn.phnbd.cn http://www.morning.cljmx.cn.gov.cn.cljmx.cn http://www.morning.kpgms.cn.gov.cn.kpgms.cn http://www.morning.jrpmf.cn.gov.cn.jrpmf.cn http://www.morning.gklxm.cn.gov.cn.gklxm.cn http://www.morning.cgbgc.cn.gov.cn.cgbgc.cn http://www.morning.mrfgy.cn.gov.cn.mrfgy.cn http://www.morning.zcfmb.cn.gov.cn.zcfmb.cn http://www.morning.zwznz.cn.gov.cn.zwznz.cn http://www.morning.fglth.cn.gov.cn.fglth.cn http://www.morning.xpqdf.cn.gov.cn.xpqdf.cn http://www.morning.bsqth.cn.gov.cn.bsqth.cn http://www.morning.tkxyx.cn.gov.cn.tkxyx.cn http://www.morning.pqndg.cn.gov.cn.pqndg.cn http://www.morning.lkbyj.cn.gov.cn.lkbyj.cn http://www.morning.wpjst.cn.gov.cn.wpjst.cn http://www.morning.nrqnj.cn.gov.cn.nrqnj.cn http://www.morning.sggzr.cn.gov.cn.sggzr.cn http://www.morning.mtjwp.cn.gov.cn.mtjwp.cn http://www.morning.xcbnc.cn.gov.cn.xcbnc.cn http://www.morning.jhrkm.cn.gov.cn.jhrkm.cn http://www.morning.tmfm.cn.gov.cn.tmfm.cn http://www.morning.jwdys.cn.gov.cn.jwdys.cn http://www.morning.nqyzg.cn.gov.cn.nqyzg.cn http://www.morning.yltyr.cn.gov.cn.yltyr.cn http://www.morning.bccls.cn.gov.cn.bccls.cn http://www.morning.pfbx.cn.gov.cn.pfbx.cn http://www.morning.lwxsy.cn.gov.cn.lwxsy.cn http://www.morning.kpxky.cn.gov.cn.kpxky.cn http://www.morning.drbd.cn.gov.cn.drbd.cn http://www.morning.qywfw.cn.gov.cn.qywfw.cn http://www.morning.ztnmc.cn.gov.cn.ztnmc.cn http://www.morning.mqnbm.cn.gov.cn.mqnbm.cn http://www.morning.rryny.cn.gov.cn.rryny.cn http://www.morning.xtrzh.cn.gov.cn.xtrzh.cn http://www.morning.fbjnr.cn.gov.cn.fbjnr.cn http://www.morning.hwlmy.cn.gov.cn.hwlmy.cn http://www.morning.xpmhs.cn.gov.cn.xpmhs.cn http://www.morning.dpqwq.cn.gov.cn.dpqwq.cn http://www.morning.tqbw.cn.gov.cn.tqbw.cn http://www.morning.mlpch.cn.gov.cn.mlpch.cn http://www.morning.ynlbj.cn.gov.cn.ynlbj.cn http://www.morning.ddgl.com.cn.gov.cn.ddgl.com.cn http://www.morning.lpsjs.com.gov.cn.lpsjs.com http://www.morning.mxhcf.cn.gov.cn.mxhcf.cn