sofastack / sofa-rpc

SOFARPC is a high-performance, high-extensibility, production-level Java RPC framework.
https://www.sofastack.tech/sofa-rpc/docs/Home
Apache License 2.0
3.82k stars 1.17k forks source link

JSON.toJSONString() 序列化导致原Map的value转换为LinkedHashMap #1254

Closed bzl132 closed 1 year ago

bzl132 commented 1 year ago

Describe the bug

JSON.toJSONString() 序列化导致原Map的value转换为LinkedHashMap。

Expected behavior

JSON.toJSONString() 序列化后不影响原实体

Actual behavior

JSON序列化自定义对象时,调用BeanSerializer.serialize()将对象转换成map image 如果,自定义对象中属性是Map时,会将Value替换成递归调用的结果, image 这时如果Value是对象,会转换成LinkedHashMap,返回后会替换原始实体 image

Steps to reproduce

运行Demo的main方法

Minimal yet complete reproducer code (or GitHub URL to code)

import com.alipay.sofa.rpc.common.json.JSON; import java.util.HashMap; import java.util.Map;

public class TestDemo {

public static void main(String[] args) {
    BeanEntity bean = new TestDemo.BeanEntity();
    Map<String, ? super ValueEntity> map = new HashMap<>();
    map.put("1", new ValueEntity());
    bean.map = map;

    String jsonString = JSON.toJSONString(bean);

    bean.map.values().forEach(value -> {
        System.out.println(value.getClass().getSimpleName());
    });
}

static class BeanEntity {
    Map<String, ? super ValueEntity> map;
}

static class ValueEntity {}

}

Environment

EvenLjj commented 1 year ago

image @bzl132 Thank you for feedback. It's really a bug, there should be a new map. Are you interested to fix it?

stale[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

gofow commented 1 year ago

Hi there, I'd like to take a crack at fixing it. Would you mind assigning the issue to me? My thought is to create a fresh Map within the serialize() function when the "bean" is a Map instance, in order to prevent any unpredictable changes due to references. @OrezzerO @EvenLjj

EvenLjj commented 1 year ago

@gofow You are right, looking forward to your participation.