Fastjson解析多级泛型的几种方式—新增使用class文件来解析多级
Fastjson解析多级泛型前言现在网上大多数是使用 实例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>>>() {});
}
浏览器访问: 可以得到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},classes[i - 1]);
}
主要意思是将你的class对象包装成一个ParameterizedTypeImpl,使用ParameterizedTypeImpl来解析多级泛型,但是要注意的是,每层泛型,都需要用一个ParameterizedTypeImpl对象进行包装起来才会起作用,因为他会有一个 最后也可以正确解析哈~
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |