fastjson 1.1.61.android 出现泛型解析不彻底的情况

lg40wkob  于 2021-11-27  发布在  Java
关注(0)|答案(5)|浏览(331)
public class Resource<T> {
    private Status status;
    private int ret;
    private String message;
    private T data;
}

public class App {
    private String appId;
}

class Test<T> {
    String str= "{\"ret\":0,\"msg\":\"ok\",\"data\":[{\"appId\":\"11c53f541dee4f5bbc4f75f99002278c\"},{\"appId\":\"c6102275ce5540a59424defa1cccb8ed\"}]}";

    Test() {
        Resource<T> resource = JSON.parseObject(str, new TypeReference<Resource<T>>(){});
        Log.d(TAG, resource + "");
    }
}

调用方法为:

new Test<ArrayList<App>>();

最后ArrayList没有解析出来,而是JSONArray,是我使用方式不对吗

tgabmvqs

tgabmvqs1#

package com.alibaba.json.bvt.issue_1400;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import junit.framework.TestCase;
import org.junit.Assert;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by kimmking on 11/08/2017.
 */
public class Issue1400 extends TestCase {
    public void test_for_issue() throws Exception {
        TypeReference tr = new TypeReference<Resource<ArrayList<App>>>(){};
        Test test = new Test(tr);
        Resource resource = test.resource;
        Assert.assertEquals(1,resource.ret);
        Assert.assertEquals("ok",resource.message);
        List<App> data =(List<App>) resource.data;
        Assert.assertEquals(2,data.size());
        App app1 = data.get(0);
        Assert.assertEquals("11c53f541dee4f5bbc4f75f99002278c",app1.appId);
    }

    public static class Resource<T> {
        public int ret;
        public String message;
        public T data;
    }

    public static class App {
        public String appId;
    }

    public static class Test {
        String str = "{\"ret\":1,\"message\":\"ok\",\"data\":[{\"appId\":\"11c53f541dee4f5bbc4f75f99002278c\"},{\"appId\":\"c6102275ce5540a59424defa1cccb8ed\"}]}";
        public Resource resource;
        Test(TypeReference tr) {
            resource = (Resource)JSON.parseObject(str, tr);
        }
    }
}
b91juud3

b91juud32#

@kimmking hello,你这样写是没问题的,因为在new TypeReference<Resource<ArrayList<App>>>(){}已经指定是ArrayList<App>了,
我这边是用的泛型new TypeReference<Resource<T>>(){},这样只能解成JSONArray

8wtpewkr

8wtpewkr4#

@wenshao

public static <T> Response<T> parseToMap(String json, Class<T> type) {
    return JSON.parseObject(json,  new TypeReference<Response<T>>(type) {});
}

我在处理数据的过程中怎么拿到第二个参数type呢。

我想到的种方式是
Responseextend一个super class,在super class中拿到泛型的类型

public class BaseResponse<T> {
    private Class<T> genericType;

    public BaseResponse() {
       genericType = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
   }

   public Class<T> getGenericType() {
       return genericType;
   }
}

然后在解析时

Response response = new Response();
Response realResp = parseToMap(jsonStr, response.getGenericType());

感觉这样好麻烦,还有别的调用方式吗

wooyq4lh

wooyq4lh5#

@wenshao@kimmking 麻烦看下上面的问题

相关问题