From 1d9d9a327ef06960189cf0e9f026904d37d01ae9 Mon Sep 17 00:00:00 2001
From: liyj <1003249715@qq.com>
Date: Mon, 02 Sep 2024 11:22:42 +0800
Subject: [PATCH] 1、网关请求响应格式修改
---
dyh-gateway/src/main/java/cn/huge/gateway/filter/AuthFilter.java | 6 +
dyh-gateway/src/main/java/cn/huge/gateway/utils/JsonMapper.java | 212 +++++++++++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 216 insertions(+), 2 deletions(-)
diff --git a/dyh-gateway/src/main/java/cn/huge/gateway/filter/AuthFilter.java b/dyh-gateway/src/main/java/cn/huge/gateway/filter/AuthFilter.java
index 4396a41..5c299ad 100644
--- a/dyh-gateway/src/main/java/cn/huge/gateway/filter/AuthFilter.java
+++ b/dyh-gateway/src/main/java/cn/huge/gateway/filter/AuthFilter.java
@@ -1,5 +1,6 @@
package cn.huge.gateway.filter;
+import cn.huge.gateway.utils.JsonMapper;
import cn.huge.gateway.utils.ReturnBO;
import cn.huge.gateway.utils.SpringContextUtil;
import com.auth0.jwt.JWT;
@@ -84,6 +85,7 @@
if (status) {
return chain.filter(exchange);
} else {
+ JsonMapper jsonMapper = new JsonMapper();
ReturnBO returnBO = new ReturnBO();
//从请求头中取出token
String token = exchange.getRequest().getHeaders().getFirst("Authorization");
@@ -94,7 +96,7 @@
originalResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
returnBO.setCode(401);
returnBO.setMsg("您尚未登录,请登录后重试!");
- byte[] response = returnBO.toString().getBytes(StandardCharsets.UTF_8);
+ byte[] response = jsonMapper.toJson(returnBO).getBytes(StandardCharsets.UTF_8);
DataBuffer buffer = originalResponse.bufferFactory().wrap(response);
return originalResponse.writeWith(Flux.just(buffer));
} else {
@@ -104,7 +106,7 @@
ServerHttpResponse originalResponse = exchange.getResponse();
originalResponse.setStatusCode(HttpStatus.OK);
originalResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
- byte[] response = returnBO.toString().getBytes(StandardCharsets.UTF_8);
+ byte[] response = jsonMapper.toJson(returnBO).getBytes(StandardCharsets.UTF_8);
DataBuffer buffer = originalResponse.bufferFactory().wrap(response);
return originalResponse.writeWith(Flux.just(buffer));
} else {
diff --git a/dyh-gateway/src/main/java/cn/huge/gateway/utils/JsonMapper.java b/dyh-gateway/src/main/java/cn/huge/gateway/utils/JsonMapper.java
new file mode 100644
index 0000000..569dfea
--- /dev/null
+++ b/dyh-gateway/src/main/java/cn/huge/gateway/utils/JsonMapper.java
@@ -0,0 +1,212 @@
+package cn.huge.gateway.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.DeserializationFeature;
+import com.fasterxml.jackson.databind.JavaType;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
+import com.fasterxml.jackson.databind.util.JSONPObject;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+
+/**
+ * @title: JSON工具类
+ * @description: JSON工具类
+ * @company: hugeinfo
+ * @author: liyj
+ * @time: 2021-11-05 16:51:48
+ * @version: 1.0.0
+ */
+public class JsonMapper {
+ private static Logger logger = LoggerFactory.getLogger(JsonMapper.class);
+ private ObjectMapper mapper;
+
+ /**
+ * 构造函数
+ */
+ public JsonMapper() {
+ this(null);
+ }
+
+ /**
+ * 构造函数
+ * @param include
+ */
+ public JsonMapper(JsonInclude.Include include) {
+ this.mapper = new ObjectMapper();
+
+ if (include != null) {
+ this.mapper.setSerializationInclusion(include);
+ }
+
+ this.mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
+ }
+
+ /**
+ * 创建非空JsonMapper
+ * @return JsonMapper
+ */
+ public static JsonMapper nonEmptyMapper() {
+ return new JsonMapper(JsonInclude.Include.NON_EMPTY);
+ }
+
+ /**
+ * 创建非默认JsonMapper
+ * @return JsonMapper
+ */
+ public static JsonMapper nonDefaultMapper() {
+ return new JsonMapper(JsonInclude.Include.NON_DEFAULT);
+ }
+
+ /**
+ * 对象转json字符串
+ * @param object 对象
+ * @return String
+ */
+ public String toJson(Object object) {
+ try
+ {
+ return this.mapper.writeValueAsString(object);
+ } catch (IOException e) {
+ logger.warn("write to json string error:" + object, e);
+ }return null;
+ }
+
+ /**
+ * json字符串转对象
+ * @param jsonString json字符串
+ * @param clazz 类
+ * @param <T> 对象
+ * @return T
+ */
+ public <T> T fromJson(String jsonString, Class<T> clazz) {
+ if (StringUtils.isEmpty(jsonString)) {
+ return null;
+ }
+ try
+ {
+ return this.mapper.readValue(jsonString, clazz);
+ } catch (IOException e) {
+ logger.warn("parse json string error:" + jsonString, e);
+ }return null;
+ }
+
+ /**
+ * json字符串转对象
+ * @param jsonString json字符串
+ * @param type 类型
+ * @param <T> 对象
+ * @return T
+ */
+ public <T> T fromJson(String jsonString, TypeReference<T> type) {
+ if (StringUtils.isEmpty(jsonString)) {
+ return null;
+ }
+ try
+ {
+ return this.mapper.readValue(jsonString, type);
+ } catch (IOException e) {
+ logger.warn("parse json string error:" + jsonString, e);
+ }return null;
+ }
+
+ /**
+ * json字符串转对象
+ * @param jsonString json字符串
+ * @param javaType java类型
+ * @param <T> 对象
+ * @return T
+ */
+ public <T> T fromJson(String jsonString, JavaType javaType) {
+ if (StringUtils.isEmpty(jsonString)) {
+ return null;
+ }
+ try
+ {
+ return this.mapper.readValue(jsonString, javaType);
+ } catch (IOException e) {
+ logger.warn("parse json string error:" + jsonString, e);
+ }return null;
+ }
+
+ /**
+ * 创建数组类型
+ * @param collectionClass 数组类型
+ * @param elementClasses 对象类
+ * @return JavaType
+ */
+ public JavaType createCollectionType(Class<?> collectionClass, Class<?>[] elementClasses) {
+ return this.mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
+ }
+
+ /**
+ * 更新
+ * @param jsonString json字符串
+ * @param object 对象
+ * @return T
+ */
+ public <T> T update(String jsonString, T object) {
+ try
+ {
+ return this.mapper.readerForUpdating(object).readValue(jsonString);
+ } catch (JsonProcessingException e) {
+ logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
+ } catch (IOException e) {
+ logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
+ }
+ return null;
+ }
+
+ /**
+ * 转JsonP
+ * @param functionName 函数名
+ * @param object 对象
+ * @return String
+ */
+ public String toJsonP(String functionName, Object object) {
+ return toJson(new JSONPObject(functionName, object));
+ }
+
+ /**
+ * 转字符串
+ */
+ public void enableEnumUseToString() {
+ this.mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
+ this.mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
+ }
+
+ /**
+ * 获取ObjectMapper
+ * @return ObjectMapper
+ */
+ public ObjectMapper getMapper() {
+ return this.mapper;
+ }
+}
+/**
+ * -------------------_ooOoo_-------------------
+ * ------------------o8888888o------------------
+ * ------------------88" . "88------------------
+ * ------------------(| -_- |)------------------
+ * ------------------O\ = /O------------------
+ * ---------------____/`---'\____---------------
+ * -------------.' \\| |// `.-------------
+ * ------------/ \\||| : |||// \------------
+ * -----------/ _||||| -:- |||||- \-----------
+ * -----------| | \\\ - /// | |-----------
+ * -----------| \_| ''\---/'' | |-----------
+ * -----------\ .-\__ `-` ___/-. /-----------
+ * ---------___`. .' /--.--\ `. . __----------
+ * ------."" '< `.___\_<|>_/___.' >'"".-------
+ * -----| | : `- \`.;`\ _ /`;.`/ - ` : | |-----
+ * -----\ \ `-. \_ __\ /__ _/ .-` / /-----
+ * ======`-.____`-.___\_____/___.-`____.-'======
+ * -------------------`=---='
+ * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ * ---------佛祖保佑---hugeinfo---永无BUG----------
+ */
--
Gitblit v1.8.0