Skip to content
This repository has been archived by the owner on Oct 23, 2024. It is now read-only.

同时使用 Class 和 ParameterizedType 解析 json 时,ParameterizedType解析出错 #4402

Open
hxliu opened this issue May 30, 2023 · 0 comments

Comments

@hxliu
Copy link

hxliu commented May 30, 2023

fastjson 版本:1.2.76

问题:同时使用简单类型、嵌套类型解析时,会导致 嵌套类型解析 解析失败。

测试代码:

package any;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.util.List;
import java.util.Map;

public class Test {
    static class Result<T> {
        public T data;
        public int code;
    }

    public static void main(String[] args) throws Exception {
        String json = "{\"data\":[{}]}";
        // 这一步缓存 Result.class 的解析器
        JSON.parseObject(json, Result.class);

        // 嵌套类型解析 Result<List<Map>>
        Result res = JSON.parseObject(json, new TypeReference<Result<List<Map>>>() {});

        // 返回了 class com.alibaba.fastjson.JSONArray
        System.out.println(res.data.getClass());
    }
}

源代码:
com.alibaba.fastjson.parser.ParserConfig 617 行

    public ObjectDeserializer getDeserializer(Class<?> clazz, Type type) {
        ObjectDeserializer deserializer = get(type);
        if (deserializer == null && type instanceof ParameterizedTypeImpl) {
            Type innerType = TypeReference.intern((ParameterizedTypeImpl) type);
            deserializer = get(innerType);
        }

        if (deserializer != null) {
            return deserializer;
        }

        if (type == null) {
            type = clazz;
        }

        deserializer = get(type);
        if (deserializer != null) {
            return deserializer;
        }

        {
            JSONType annotation = TypeUtils.getAnnotation(clazz,JSONType.class);
            if (annotation != null) {
                Class<?> mappingTo = annotation.mappingTo();
                if (mappingTo != Void.class) {
                    return getDeserializer(mappingTo, mappingTo);
                }
            }
        }

        // 注意:本步从缓存中取出了简单类型的解析器,导致嵌套类型解析器无法生成
        if (type instanceof WildcardType || type instanceof TypeVariable || type instanceof ParameterizedType) {
            deserializer = get(clazz);
        }

        if (deserializer != null) {
            return deserializer;
        }
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant