带有API接口交互的web项目开发过程中,json字符串与javaBean对象之间的相互转换是比较常见的需求,基于jackson ObjectMapper 实现的工具类较好的满足了此需求。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webflux</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>io.projectreactor.netty</groupId>
<artifactId>reactor-netty</artifactId>
<version>0.9.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.12.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.5.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
JsonBeanUtils
import java.io.IOException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* JsonBean转换工具
*
* @author 00fly
*
*/
public class JsonBeanUtils
{
private static ObjectMapper objectMapper = new ObjectMapper();
/**
* bean转json字符串
*
* @param bean
* @return
* @throws IOException
*/
public static String beanToJson(Object bean)
throws IOException
{
String jsonText = objectMapper.writeValueAsString(bean);
return objectMapper.readTree(jsonText).toPrettyString();
}
/**
* json字符串转bean
*
* @param jsonText
* @return
* @throws IOException
*/
public static <T> T jsonToBean(String jsonText, Class<T> clazz)
throws IOException
{
return objectMapper.readValue(jsonText, clazz);
}
/**
* json字符串转bean
*
* @param jsonText
* @return
* @throws IOException
*/
public static <T> T jsonToBean(String jsonText, JavaType javaType)
throws IOException
{
return objectMapper.readValue(jsonText, javaType);
}
/**
* json字符串转bean
*
* @param jsonText
* @return
* @throws IOException
*/
public static <T> T jsonToBean(String jsonText, TypeReference<T> typeRef)
throws IOException
{
return objectMapper.readValue(jsonText, typeRef);
}
}
jdbc.properties
druid.username=sa
druid.password=
druid.url=jdbc:h2:mem:hello;database_to_upper=false
druid.driverClassName=org.h2.Driver
data.json
{
"code": 200,
"message": "success",
"traceId": "fcd55497-864a-4d74-9db0-69a04655184f",
"data": {
"list": [
{
"articleId": 135418954,
"title": "java解析json复杂数据的两种思路",
"description": "萌新小明最近新开了CSDN博客,蠢蠢欲动,迫不及待的发表了几篇工作中积累下来的解决问题的涂鸦之作,看着访问量慢慢涨起来,心中暗暗窃喜。现在小明想每天23点记录一下每篇文章的访问量。。。",
"url": "https://blog.csdn.net/qq_16127313/article/details/135418954",
"type": 1,
"top": false,
"forcePlan": false,
"viewCount": 828,
"commentCount": 0,
"editUrl": "https://editor.csdn.net/md?articleId=135418954",
"postTime": "2024-01-06 14:11:40",
"diggCount": 16,
"formatTime": "前天 14:11",
"picList": [
"https://img-blog.csdnimg.cn/direct/a409a0f4555c459fa05c00fd9ee0ea8c.png"
],
"collectCount": 19
},
{
"articleId": 135244727,
"title": "java lambda表达式训练题一",
"description": "Lambda 表达式,也可称为闭包,它是推动 Java 8 发布的最重要新特性。Lambda 允许把函数作为一个方法的参数(函数作为参数传递进方法中)。使用 Lambda 表达式可以使代码变的更加简洁紧凑。",
"url": "https://blog.csdn.net/qq_16127313/article/details/135244727",
"type": 1,
"top": false,
"forcePlan": false,
"viewCount": 1238,
"commentCount": 0,
"editUrl": "https://editor.csdn.net/md?articleId=135244727",
"postTime": "2023-12-27 18:07:30",
"diggCount": 7,
"formatTime": "2023.12.27",
"picList": [
"https://img-blog.csdnimg.cn/direct/d59c68b950754e879914b5319cd1b53f.png"
],
"collectCount": 8
},
{
"articleId": 135173565,
"title": "二维码初体验 com.google.zxing 实现续 - web api封装",
"description": "在 二维码初体验 com.google.zxing 实现 我们实现了二维码的生成,但是大部分情况下,二维码的相关功能是作为API接口来提供服务的。我们下面便演示在springboot、Knife4j下封装api接口来实现二维码生成功能。如何使用下面的备份文件恢复成原始的项目代码,请移步查阅:神奇代码恢复工具-over-",
"url": "https://blog.csdn.net/qq_16127313/article/details/135173565",
"type": 1,
"top": false,
"forcePlan": false,
"viewCount": 1904,
"commentCount": 0,
"editUrl": "https://editor.csdn.net/md?articleId=135173565",
"postTime": "2023-12-23 20:17:11",
"diggCount": 23,
"formatTime": "2023.12.23",
"picList": [
"https://img-blog.csdnimg.cn/direct/f0c994ca789a495a8c8c03d86d626f24.jpeg"
],
"collectCount": 23
},
{
"articleId": 135167613,
"title": "二维码初体验 com.google.zxing 实现",
"description": "Java 操作二维码的开源项目很多,如 SwetakeQRCode、BarCode4j、Zxing 等,这边以Zxing 为例进行介绍。选择需要生成QR原始文件,支持 “清除空白行及空格” 以减少二维码图片大小。支持输入文本内容,直接生成二维码代码结构QrCodeUI: 完整版本代码SimpleQrCodeUI:简化版本代码如何使用下面的备份文件恢复成原始的项目代码,请移步查阅:神奇代码恢复工具-over-",
"url": "https://blog.csdn.net/qq_16127313/article/details/135167613",
"type": 1,
"top": false,
"forcePlan": false,
"viewCount": 1286,
"commentCount": 0,
"editUrl": "https://editor.csdn.net/md?articleId=135167613",
"postTime": "2023-12-23 13:52:23",
"diggCount": 6,
"formatTime": "2023.12.23",
"picList": [
"https://img-blog.csdnimg.cn/direct/d3eeac85857543869dce8967c570bdc4.jpeg"
],
"collectCount": 11
},
{
"articleId": 135135799,
"title": "【随笔】MD5加密字符串、文件apache、springframework实现",
"description": "【代码】【随笔】MD5加密字符串、文件commons-codec、springframework实现。",
"url": "https://blog.csdn.net/qq_16127313/article/details/135135799",
"type": 1,
"top": false,
"forcePlan": false,
"viewCount": 1721,
"commentCount": 0,
"editUrl": "https://editor.csdn.net/md?articleId=135135799",
"postTime": "2023-12-21 17:29:54",
"diggCount": 9,
"formatTime": "2023.12.21",
"picList": [
"https://img-blog.csdnimg.cn/direct/dc26b7f1c731494f80c8c3b3badfa95d.jpeg"
],
"collectCount": 9
}
],
"total": 72
}
}
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Properties;
import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
/**
* JsonBeanUtils测试
*/
@Slf4j
public class JsonBeanUtilsTest
{
static String jsonText;
static Properties properties;
static WebClient webClient;
static String url;
@BeforeAll
public static void init()
{
try
{
properties = PropertiesLoaderUtils.loadProperties(new ClassPathResource("jdbc.properties"));
jsonText = IOUtils.toString(new ClassPathResource("data.json").getURL(), StandardCharsets.UTF_8);
webClient = WebClient.builder().codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)).build();
url = "https://blog.csdn.net/community/home-api/v1/get-business-list?page=1&size=5&businessType=blog&username=qq_16127313";
}
catch (IOException e)
{
log.error(e.getMessage(), e);
}
}
@Test
public void propsTest()
throws IOException
{
String propsJson = JsonBeanUtils.beanToJson(properties);
log.info("propsJson : {} ", propsJson);
log.info("properties: {} ", JsonBeanUtils.jsonToBean(propsJson, Properties.class));
}
@Test
public void beanToJson001()
throws IOException
{
BlogData blogData = JsonBeanUtils.jsonToBean(jsonText, BlogData.class);
log.info("blogData: {} ", blogData);
log.info("blogData: {} ", JsonBeanUtils.beanToJson(blogData));
log.info("blogData.data: {} ", JsonBeanUtils.beanToJson(blogData.getData()));
log.info("blogData.data.list: {} ", JsonBeanUtils.beanToJson(blogData.getData().getList()));
}
@Test
public void beanToJson002()
throws IOException
{
String resp = webClient.get().uri(url).acceptCharset(StandardCharsets.UTF_8).accept(MediaType.APPLICATION_JSON).retrieve().bodyToMono(String.class).block();
BlogData blogData = JsonBeanUtils.jsonToBean(resp, BlogData.class);
String jsonText = JsonBeanUtils.beanToJson(blogData);
log.info("blogData: {} ", blogData);
log.info("jsonText: {} ", jsonText);
}
/**
* 测试 JsonBeanUtils.jsonToBean(String jsonText, JavaType javaType)
*
* @throws IOException
*/
@Test
public void jsonToBean001()
throws IOException
{
BlogData blogData = JsonBeanUtils.jsonToBean(jsonText, BlogData.class);
String jsonStr = JsonBeanUtils.beanToJson(blogData.getData().getList());
// List<SubList>
JavaType javaType = TypeFactory.defaultInstance().constructParametricType(List.class, SubList.class);
List<SubList> dataEntitys = JsonBeanUtils.jsonToBean(jsonStr, javaType);
log.info("dataEntitys: {} ", dataEntitys);
}
/**
* 测试 JsonBeanUtils.jsonToBean(String jsonText, TypeReference<T> typeRef)
*
* @throws IOException
*/
@Test
public void jsonToBean002()
throws IOException
{
BlogData blogData = JsonBeanUtils.jsonToBean(jsonText, BlogData.class);
String jsonStr = JsonBeanUtils.beanToJson(blogData.getData().getList());
// List<SubList>
TypeReference<List<SubList>> typeRef = new TypeReference<List<SubList>>()
{
};
List<SubList> dataEntitys = JsonBeanUtils.jsonToBean(jsonStr, typeRef);
log.info("dataEntitys: {} ", dataEntitys);
}
}
@Data
class BlogData
{
private Integer code;
private String message;
private String traceId;
private Record data;
}
@Data
class Record
{
private List<SubList> list;
private Long total;
}
@Data
class SubList
{
String articleId;
String title;
String description;
String url;
Integer type;
String top;
String forcePlan;
Long viewCount;
Long commentCount;
String editUrl;
String postTime;
Long diggCount;
String formatTime;
Object picList;
Long collectCount;
}
如何使用下面的备份文件恢复成原始的项目代码,请移步查阅:神奇代码恢复工具
//goto pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fly</groupId>
<artifactId>base</artifactId>
<version>0.0.1</version>
<name>base</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<skipTests>true</skipTests>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webflux</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>io.projectreactor.netty</groupId>
<artifactId>reactor-netty</artifactId>
<version>0.9.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.12.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.5.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
//goto src\main\java\com\fly\core\utils\JsonBeanUtils.java
package com.fly.core.utils;
import java.io.IOException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* JsonBean转换工具
*
* @author 00fly
*
*/
public class JsonBeanUtils
{
private static ObjectMapper objectMapper = new ObjectMapper();
/**
* bean转json字符串
*
* @param bean
* @return
* @throws IOException
*/
public static String beanToJson(Object bean)
throws IOException
{
String jsonText = objectMapper.writeValueAsString(bean);
return objectMapper.readTree(jsonText).toPrettyString();
}
/**
* json字符串转bean
*
* @param jsonText
* @return
* @throws IOException
*/
public static <T> T jsonToBean(String jsonText, Class<T> clazz)
throws IOException
{
return objectMapper.readValue(jsonText, clazz);
}
/**
* json字符串转bean
*
* @param jsonText
* @return
* @throws IOException
*/
public static <T> T jsonToBean(String jsonText, JavaType javaType)
throws IOException
{
return objectMapper.readValue(jsonText, javaType);
}
/**
* json字符串转bean
*
* @param jsonText
* @return
* @throws IOException
*/
public static <T> T jsonToBean(String jsonText, TypeReference<T> typeRef)
throws IOException
{
return objectMapper.readValue(jsonText, typeRef);
}
}
//goto src\main\resources\log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="off" monitorInterval="0">
<appenders>
<console name="Console" target="system_out">
<patternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</console>
</appenders>
<loggers>
<root level="INFO">
<appender-ref ref="Console" />
</root>
</loggers>
</configuration>
//goto src\test\java\com\fly\core\utils\JsonBeanUtilsTest.java
package com.fly.core.utils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Properties;
import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
/**
* JsonBeanUtils测试
*/
@Slf4j
public class JsonBeanUtilsTest
{
static String jsonText;
static Properties properties;
static WebClient webClient;
static String url;
@BeforeAll
public static void init()
{
try
{
properties = PropertiesLoaderUtils.loadProperties(new ClassPathResource("jdbc.properties"));
jsonText = IOUtils.toString(new ClassPathResource("data.json").getURL(), StandardCharsets.UTF_8);
webClient = WebClient.builder().codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)).build();
url = "https://blog.csdn.net/community/home-api/v1/get-business-list?page=1&size=5&businessType=blog&username=qq_16127313";
}
catch (IOException e)
{
log.error(e.getMessage(), e);
}
}
@Test
public void propsTest()
throws IOException
{
String propsJson = JsonBeanUtils.beanToJson(properties);
log.info("propsJson : {} ", propsJson);
log.info("properties: {} ", JsonBeanUtils.jsonToBean(propsJson, Properties.class));
}
@Test
public void beanToJson001()
throws IOException
{
BlogData blogData = JsonBeanUtils.jsonToBean(jsonText, BlogData.class);
log.info("blogData: {} ", blogData);
log.info("blogData: {} ", JsonBeanUtils.beanToJson(blogData));
log.info("blogData.data: {} ", JsonBeanUtils.beanToJson(blogData.getData()));
log.info("blogData.data.list: {} ", JsonBeanUtils.beanToJson(blogData.getData().getList()));
}
@Test
public void beanToJson002()
throws IOException
{
String resp = webClient.get().uri(url).acceptCharset(StandardCharsets.UTF_8).accept(MediaType.APPLICATION_JSON).retrieve().bodyToMono(String.class).block();
BlogData blogData = JsonBeanUtils.jsonToBean(resp, BlogData.class);
String jsonText = JsonBeanUtils.beanToJson(blogData);
log.info("blogData: {} ", blogData);
log.info("jsonText: {} ", jsonText);
}
/**
* 测试 JsonBeanUtils.jsonToBean(String jsonText, JavaType javaType)
*
* @throws IOException
*/
@Test
public void jsonToBean001()
throws IOException
{
BlogData blogData = JsonBeanUtils.jsonToBean(jsonText, BlogData.class);
String jsonStr = JsonBeanUtils.beanToJson(blogData.getData().getList());
// List<SubList>
JavaType javaType = TypeFactory.defaultInstance().constructParametricType(List.class, SubList.class);
List<SubList> dataEntitys = JsonBeanUtils.jsonToBean(jsonStr, javaType);
log.info("dataEntitys: {} ", dataEntitys);
}
/**
* 测试 JsonBeanUtils.jsonToBean(String jsonText, TypeReference<T> typeRef)
*
* @throws IOException
*/
@Test
public void jsonToBean002()
throws IOException
{
BlogData blogData = JsonBeanUtils.jsonToBean(jsonText, BlogData.class);
String jsonStr = JsonBeanUtils.beanToJson(blogData.getData().getList());
// List<SubList>
TypeReference<List<SubList>> typeRef = new TypeReference<List<SubList>>()
{
};
List<SubList> dataEntitys = JsonBeanUtils.jsonToBean(jsonStr, typeRef);
log.info("dataEntitys: {} ", dataEntitys);
}
}
@Data
class BlogData
{
private Integer code;
private String message;
private String traceId;
private Record data;
}
@Data
class Record
{
private List<SubList> list;
private Long total;
}
@Data
class SubList
{
String articleId;
String title;
String description;
String url;
Integer type;
String top;
String forcePlan;
Long viewCount;
Long commentCount;
String editUrl;
String postTime;
Long diggCount;
String formatTime;
Object picList;
Long collectCount;
}
//goto src\test\resources\jdbc.properties
druid.username=sa
druid.password=
druid.url=jdbc:h2:mem:hello;database_to_upper=false
druid.driverClassName=org.h2.Driver
//goto src\test\resources\log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="off" monitorInterval="0">
<appenders>
<console name="Console" target="system_out">
<patternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</console>
</appenders>
<loggers>
<root level="INFO">
<appender-ref ref="Console" />
</root>
</loggers>
</configuration>
有任何问题和建议,都可以向我提问讨论,大家一起进步,谢谢!
-over-