Fork me on GitHub

Fastjson解析多级泛型的几种方式—使用class文件来解析多级泛型

Fastjson解析多级泛型

前言

现在网上大多数是使用TypeReference 方式来解析JSON数据,这里我提供另外一种方式来解析,使用类文件进行解析,两种方式我都会给出实际代码

实例

TypeReference方式
    @GET
@Path("getUserCourse")
@Produces(MediaType.APPLICATION_JSON)
public Result<List<UserCourseDto>> getUserCourse(){
return externalBiz.getUserCourse();
}
public Result<List<UserCourseDto>> getUserCourse(){
String result = restTemplate.getForObject(MOCK_JSON_URL, String.class);
return JSONObject.parseObject(result, new TypeReference<Result<List<UserCourseDto>>>() {});
}

这里使用的基于jsr-339标准的resteasy开发demo

浏览器访问:http://localhost:8080/v1/province/getUserCourse

可以得到json返回的结果

{
status: 0,
message: "1",
data: [
{
openType: "兑换 ",
userID: 30014,
classID: 10376,
className: "趣味职场俚语课程【11月班】",
chargeFee: 106,
classStudyTime: null,
openRMB: 0,
rechargeFee: 0,
awardFee: 0,
openFee: 0,
dateAdded: 1312175789393,
expiredDate: 1323964800000
}
]
}

介绍:

这里使用了提供的TypeReference进行包装,能够清晰明了进行解析多级泛型,但是有时候,我们做一些通用的解析框架的时候,可能会用T类型,T类型拿到的是字节码文件,或者class对象,又该怎么处理呢?请看下面介绍。

class类方式

接口:

接口之类用了一个注解来处理的,没有直接传class对象过去,因为在实际项目中,基本都是注解,没有谁会直接传class对象。所以我传的Annotation数组过去啦

    @GET
@Reader(extParamClass = {Result.class,List.class,UserCourseDto.class})
@Path("getUserCourseV2")
@Produces(MediaType.APPLICATION_JSON)
public Result<List<UserCourseDto>> getUserCourseV2(){
Annotation[] annotations = new Annotation[0];
for (Method method : this.getClass().getMethods()) {
if (method.getName().equals("getUserCourseV2")){
annotations = method.getAnnotations();
}
}
return externalBiz.getUserCourseV2(annotations);
}

处理:

public Result<List<UserCourseDto>> getUserCourseV2(Annotation[] annotations) {
final Reader[] readers = {null};
if(annotations != null) {
Arrays
.stream(annotations)
.filter(annotation -> annotation.annotationType().equals(Reader.class))
.findFirst().ifPresent(x -> readers[0] = (Reader) x);
}
Class[] classes = readers[0].extParamClass();
String result = restTemplate.getForObject(MOCK_JSON_URL, String.class);
//这里不用TypeReference方式,直接用class对象来处理

ParameterizedTypeImpl beforeType = null;
if (classes.length!=0){
//支持多级泛型的解析
for (int i = classes.length-1; i >0 ; i--) {
beforeType = new ParameterizedTypeImpl(new Type[]{beforeType == null? classes[i]:beforeType}, null, classes[i - 1]);
}
}
return JSON.parseObject(result,beforeType);
}

代码评析:

主要起作用的还是这两行代码

for (int i = classes.length-1; i >0 ; i--) {
beforeType = new ParameterizedTypeImpl(new Type[]{beforeType == null? classes[i]:beforeType}, null, classes[i - 1]);
}

主要意思是将你的class对象包装成一个ParameterizedTypeImpl,使用ParameterizedTypeImpl来解析多级泛型,但是要注意的是,每层泛型,都需要用一个ParameterizedTypeImpl对象进行包装起来才会起作用,因为他会有一个actualTypeArguments 和一个 rawType ,在多级泛型中,用我这里的例子说明,第一层的时候rawType 会是一个Result对象,而actualTypeArguments 会是一个包装过后的ParameterizedTypeImpl对象,第二层的时候,rawType 会是一个List对象,而actualTypeArguments 会是包装上一层的对象。后同。PS : 如果这里不知道我说的是什么,请调试的时候结合来看哈

最后也可以正确解析哈~

END

posted @ 2017-08-25 14:43  itar  阅读(14555)  评论(0编辑  收藏  举报