alibaba JSON TypeReference 複雜型別轉換
阿新 • • 發佈:2018-11-11
1. 基礎使用
在fastjson中提供了一個用於處理泛型反序列化的類TypeReference。
import com.alibaba.fastjson.TypeReference; List<VO> list = JSON.parseObject("...", new TypeReference<List<VO>>() {});
如下寫法有更好的效能
import com.alibaba.fastjson.TypeReference; final static Type type = new TypeReference<List<VO>>() {}.getType(); List<VO> list = JSON.parseObject("...", type);
在這裡例子中,通過TypeReference能夠解決List中T的型別問題。
2. 帶引數使用
在1.2.9 & 1.1.49.android版本中,TypeReference支援泛型引數,方便一些框架實現通用的反序列化類。用法如下:
2.1. 單引數例子
public class Response<T> { public T data; } public static <T> Response<T> parseToMap(String json, Class<T> type) { return JSON.parseObject(json, new TypeReference<Response<T>>(type) {}); }
2.2. 雙引數例子
public static <K, V> Map<K, V> parseToMap(String json, Class<K> keyType, Class<V> valueType) { return JSON.parseObject(json, new TypeReference<Map<K, V>>(keyType, valueType) { }); } // 可以這樣使用 String json = "{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);