[alibaba/fastjson]TypeReference泛型参数中的JSONField不生效

2025-10-29 549 views
0

帮忙看下泛型参数中的JSONField如何生效?

public static <T> RpcRespObj<T> convertResult(Class<T> type) {
        String str = "{\"status\":0,\"data\":{\"resourceId\":2,\"resourceName\":\"own佛恩\",\"systemCode\":\"ad\"}}";
        RpcRespObj<T> result = JSON.parseObject(str, new TypeReference<RpcRespObj<T>>(type) {});
        return result;
}

public static void main(String[] args) {
        RpcRespObj<Resource> resources = RbacController.convertResult(Resource.class);
        System.out.println("value:" + resources);
}

public class RpcRespObj<T> {
    private Integer status;
    private Integer errcode;
    private Integer errno;
    private T data;
}

public class Resource {
    @JSONField(name = "resource----id")
    private Integer resourceId;
    @JSONField(name = "resource----name")
    private String resourceName;
    private String systemCode;
}

运行结果:

value:RpcRespObj(status=0, errcode=null, errno=null, data=Resource(resourceId=2, resourceName=own佛恩,  systemCode=ad))

可以看到 JSONField 重命名并没有生效

回答

8

@wenshao 帮忙看下~

2

测试发现理解错了概念。JSONField中的 name 不是重命名,字段名和 JSONField->name中指定的名称,都能转换,没问题了。

1

顺道问下,RpcRespObj<T>RpcRespObj<List<Resource>> 这种形式的话,这里怎么写呢?谢谢~

JSON.parseObject(str, new TypeReference<RpcRespObj<T>>(type) {});