diff --git a/core/common/src/main/java/com/alipay/sofa/rpc/common/json/BeanSerializer.java b/core/common/src/main/java/com/alipay/sofa/rpc/common/json/BeanSerializer.java index 85cec8437..5b2fddc04 100644 --- a/core/common/src/main/java/com/alipay/sofa/rpc/common/json/BeanSerializer.java +++ b/core/common/src/main/java/com/alipay/sofa/rpc/common/json/BeanSerializer.java @@ -84,7 +84,7 @@ public static Object serialize(Object bean, boolean addType) throws NullPointerE } return array; } else if (bean instanceof Map) { - Map map = (Map) bean; + Map map = new LinkedHashMap<>((Map) bean); Iterator itr = map.entrySet().iterator(); Map.Entry entry = null; while (itr.hasNext()) { @@ -131,8 +131,11 @@ public static Object serialize(Object bean, boolean addType) throws NullPointerE + "." + field.getName() + " error! ", e); } } + if (map.size() == 0) { + addType = true; + } if (addType) { - String typeName = beanClass.getCanonicalName(); + String typeName = beanClass.getName(); if (!typeName.startsWith("java.") && !typeName.startsWith("javax.") && !typeName.startsWith("sun.")) { diff --git a/test/test-common/src/main/java/com/alipay/sofa/rpc/test/JSONTest.java b/test/test-common/src/main/java/com/alipay/sofa/rpc/test/JSONTest.java new file mode 100644 index 000000000..8d31ac0a4 --- /dev/null +++ b/test/test-common/src/main/java/com/alipay/sofa/rpc/test/JSONTest.java @@ -0,0 +1,37 @@ +package com.alipay.sofa.rpc.test; + +import com.alipay.sofa.rpc.common.json.JSON; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author github.com/gofow + * @date 2023/02/18 16:55 + **/ +public class JSONTest { + + public static void main(String[] args) { + BeanEntity bean = new JSONTest.BeanEntity(); + + Map map = new HashMap<>(); + map.put("1", new ValueEntity()); + bean.map = map; + + String jsonString = JSON.toJSONString(bean); + System.out.println(jsonString); + + bean.map.values().forEach(value -> { + System.out.println(value.getClass().getSimpleName()); + }); + + BeanEntity ans = JSON.parseObject(jsonString, BeanEntity.class); + System.out.println(ans.map.get("1").getClass().getSimpleName()); + } + + static class BeanEntity { + Map map; + } + + static class ValueEntity {} +}