alibaba / fastjson2

🚄 FASTJSON2 is a Java JSON library with excellent performance.
Apache License 2.0
3.79k stars 495 forks source link

[BUG] 反序列化错误 #2946

Open monkey1993 opened 2 months ago

monkey1993 commented 2 months ago

问题描述

反序列化错误

环境信息

请填写以下信息:

重现步骤

共计两个错误,直接运行test方法即可,错误1:

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter.Feature;
import com.alibaba.fastjson2.filter.Filter;
import org.junit.jupiter.api.Test;

import java.util.LinkedHashMap;
import java.util.Map;

public class JsonTest {

    static final Filter filter = JSONReader.autoTypeFilter("JsonTest");

    public static class User {

        public final Map<String, Module> modules = new LinkedHashMap<>();
    }

    public static class Module {
    }

    @Test
    public void test() {
        User user = new User();
        user.modules.put("1", new Module());
        String json = JSONObject.toJSONString(user, Feature.WriteClassName);
        JSON.parseObject(json, User.class, filter);
    }
}

错误2:

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter.Feature;
import com.alibaba.fastjson2.filter.Filter;
import org.junit.jupiter.api.Test;

import java.util.LinkedHashMap;
import java.util.Map;

public class JsonTest {

    static final Filter filter = JSONReader.autoTypeFilter("JsonTest");

    public static class User {

        public final Map<String, Integer> modules = new LinkedHashMap<>();
    }

    @Test
    public void test() {
        User user = new User();
        user.modules.put("1", 100);
        String json = JSONObject.toJSONString(user, Feature.WriteClassName);
        JSON.parseObject(json, User.class, filter);
    }
}

期待的正确结果

正确反序列化

相关日志输出

运行代码即可

附加信息

GabrielHwang commented 2 months ago

JSON.parseObject(json, User.class, filter,JSONReader.Feature.SupportAutoType);

我在反序列化时加了个Feature可以解决这个问题,不过这个feature好像过时了

wenshao commented 2 months ago

关于使用autoType看这个文档 https://github.com/alibaba/fastjson2/wiki/fastjson2_autotype_cn