Skip to content
This repository was archived by the owner on Jul 29, 2026. It is now read-only.

TypeReference

温绍 edited this page Nov 3, 2017 · 8 revisions

1. 基础使用

在fastjson中提供了一个用于处理泛型反序列化的类TypeReference。

importcom.alibaba.fastjson.TypeReference;
List<VO> list = JSON.parseObject("...", newTypeReference<List<VO>>() {});

如下写法有更好的性能

importcom.alibaba.fastjson.TypeReference;
finalstaticTypetype = newTypeReference<List<VO>>() {}.getType();
List<VO> list = JSON.parseObject("...", type);

在这里例子中,通过TypeReference能够解决List中T的类型问题。

2. 带参数使用

在1.2.9 & 1.1.49.android版本中,TypeReference支持泛型参数,方便一些框架实现通用的反序列化类。用法如下:

2.1. 单参数例子

publicclassResponse<T> {
publicTdata;
}
publicstatic <T> Response<T> parseToMap(Stringjson, Class<T> type) {
returnJSON.parseObject(json, newTypeReference<Response<T>>(type) {});
}

2.2. 双参数例子

publicstatic <K, V> Map<K, V> parseToMap(Stringjson, Class<K> keyType, Class<V> valueType) {
returnJSON.parseObject(json, newTypeReference<Map<K, V>>(keyType, valueType) {
});
}
// 可以这样使用Stringjson = "{1:{name:\"ddd\"},2:{name:\"zzz\"}}";
Map<Integer, Model> map = parseToMap(json, Integer.class, Model.class);
assertEquals("ddd", map.get(1).name);
assertEquals("zzz", map.get(2).name);

Clone this wiki locally