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

TypeReference解析嵌套泛型报错 #3448

@pymBupt

Description

@pymBupt
package com.alibaba.json.bvt.issue_3300;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

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

import junit.framework.TestCase;
import org.junit.Test;

/**
 * @author yumin.pym
 */
public class Issue3448 extends TestCase {
    public static class SelfTypeReference<T> {

    }

    @Test
    public void test() {
        List<Map<String, List<String>>> list = new ArrayList<>(4);
        list.add(Collections.singletonMap("key1", Collections.singletonList("item")));
        String text = JSON.toJSONString(list);
        System.out.println("text = " + text);

        List<Map<String, List<String>>> result = parseObject(text,
            new SelfTypeReference<Map<String, List<String>>>() {});
        System.out.println("result = " + result);
    }

    public <T> List<T> parseObject(String text, SelfTypeReference<T> selfTypeReference) {
        Type genericSuperclass = selfTypeReference.getClass().getGenericSuperclass();
        Type[] actualTypeArguments = ((ParameterizedType)genericSuperclass).getActualTypeArguments();
        return JSON.parseObject(text, new TypeReference<List<T>>(actualTypeArguments) {});
    }
}

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions