From 8bb17b85f2f459da3e601b00a3fb1c6d639b37aa Mon Sep 17 00:00:00 2001 From: TomlongTK Date: Tue, 11 Jul 2023 12:49:07 +0800 Subject: [PATCH] GsonUtils provide toJson method, GenericFilter use gson mode support toJson (#12633) Co-authored-by: Albumen Kevin --- .../java/org/apache/dubbo/common/json/GsonUtils.java | 11 +++++++++++ .../org/apache/dubbo/rpc/filter/GenericFilter.java | 7 +++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/json/GsonUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/json/GsonUtils.java index 7416aa5628b..4072f023a8f 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/json/GsonUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/json/GsonUtils.java @@ -60,6 +60,17 @@ public static Object fromJson(String json, Type originType) throws RuntimeExcept } } + public static String toJson(Object obj) throws RuntimeException { + if (!isSupportGson()) { + throw new RuntimeException("Gson is not supported. Please import Gson in JVM env."); + } + try { + return getGson().toJson(obj); + } catch (JsonSyntaxException ex) { + throw new RuntimeException(String.format("Generic serialization [%s] Json syntax exception thrown when parsing (object:%s ) error:%s", GENERIC_SERIALIZATION_GSON, obj, ex.getMessage())); + } + } + private static Gson getGson() { if (gsonCache == null || !(gsonCache instanceof Gson)) { synchronized (GsonUtils.class) { diff --git a/dubbo-plugin/dubbo-plugin-generic-invoke/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java b/dubbo-plugin/dubbo-plugin-generic-invoke/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java index 8375298508a..15cdefb2f4d 100644 --- a/dubbo-plugin/dubbo-plugin-generic-invoke/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java +++ b/dubbo-plugin/dubbo-plugin-generic-invoke/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java @@ -244,6 +244,9 @@ public void onResponse(Result appResponse, Invoker invoker, Invocation inv) { } appResponse.setException(appException); } + if (ProtocolUtils.isGenericReturnRawResult(generic)) { + return; + } if (ProtocolUtils.isJavaGenericSerialization(generic)) { try { UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(512); @@ -270,8 +273,8 @@ public void onResponse(Result appResponse, Invoker invoker, Invocation inv) { GENERIC_SERIALIZATION_PROTOBUF + "] serialize result failed.", e); } - } else if (ProtocolUtils.isGenericReturnRawResult(generic)) { - return; + } else if (ProtocolUtils.isGsonGenericSerialization(generic)) { + appResponse.setValue(GsonUtils.toJson(appResponse.getValue())); } else { appResponse.setValue(PojoUtils.generalize(appResponse.getValue())); }