前面兩篇文章介紹了基於okHttp的post、get請求,以及文件的上傳下載,今天主要介紹一下如何和Json解析一塊兒使用?如何才能提升開發效率?html
okHttp相關文章地址:java
本文的Json解析採用阿里巴巴的FastJson 解析,也能夠採用Gson解析,二者之間的對比請參考文章Android之json解析(FastJson Gson 對比)(http://www.cnblogs.com/whoislcj/p/5468420.html)。編程
本文將採用json統一泛型解析,閱讀本文以前請先對java泛型知識有必定的瞭解。json
本文會採用Java的反射機制來解析泛型對象Class<?>,閱讀本文以前請先對Java發射機制知識有必定的瞭解。數組
import java.lang.reflect.Array; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; public class TypeInfo { //Type泛型對象類型 private Class<?> componentType; //Type所屬對象類型 private Class<?> rawType; //type private Type type; private TypeInfo(Class<?> rawType, Class<?> componentType) { this.componentType = componentType; this.rawType = rawType; } public static TypeInfo createArrayType(Class<?> componentType) { return new TypeInfo(Array.class, componentType); } public static TypeInfo createNormalType(Class<?> componentType) { return new TypeInfo(null, componentType); } public static TypeInfo createParameterizedType(Class<?> rawType, Class<?> componentType) { return new TypeInfo(rawType, componentType); } public TypeInfo(Type type) { this.type = type; if (type instanceof ParameterizedType) { //返回 Type 對象,表示聲明此類型的類或接口。 this.rawType = (Class<?>) ((ParameterizedType) type).getRawType(); //getActualTypeArguments()返回表示此類型實際類型參數的 Type 對象的數組。 Type[] actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments(); this.componentType = (Class<?>) actualTypeArguments[0]; // typeReference=new TypeReference<Map<componentType,componentType>>(){}; } else if (type instanceof GenericArrayType) { //返回 Type 對象,表示聲明此類型的類或接口。 this.rawType = Array.class; // 表示一種元素類型是參數化類型或者類型變量的數組類型 this.componentType = (Class<?>) ((GenericArrayType) type).getGenericComponentType(); } else { this.componentType = (Class<?>) type; } } public Type getType() { return type; } public Class<?> getComponentType() { return componentType; } public Class<?> getRawType() { return rawType; } }
import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; public class ReqClassUtils { public static TypeInfo getCallbackGenericType(Class<?> clazz) { //得到帶有泛型的父類 Type genericSuperclass = clazz.getGenericSuperclass();//Type是 Java 編程語言中全部類型的公共高級接口。它們包括原始類型、參數化類型、數組類型、類型變量和基本類型。 TypeInfo type = getGetnericType(genericSuperclass); if (type == null) { Type[] genericInterfaces = clazz.getGenericInterfaces(); if (genericInterfaces != null && genericInterfaces.length > 0) { type = getGetnericType(genericInterfaces[0]); } } return type; } private static TypeInfo getGetnericType(Type type) { if (type != null && type instanceof ParameterizedType) { //getActualTypeArguments獲取參數化類型的數組,泛型可能有多個 Type[] args = ((ParameterizedType) type).getActualTypeArguments(); if (args != null && args.length > 0) { return new TypeInfo(args[0]); } } return null; } }
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; import java.lang.reflect.Array; import java.util.Collection; import java.util.HashMap; import java.util.Map; import static com.alibaba.fastjson.JSON.parseObject; public class ReqJsonUtils { //基本類型映射關係Map private static final Map primitiveWrapperTypeMap = new HashMap(8); static { //添加基本類型 primitiveWrapperTypeMap.put(Boolean.class, boolean.class); primitiveWrapperTypeMap.put(Byte.class, byte.class); primitiveWrapperTypeMap.put(Character.class, char.class); primitiveWrapperTypeMap.put(Double.class, double.class); primitiveWrapperTypeMap.put(Float.class, float.class); primitiveWrapperTypeMap.put(Integer.class, int.class); primitiveWrapperTypeMap.put(Long.class, long.class); primitiveWrapperTypeMap.put(Short.class, short.class); } /** * 將JSON字符串轉換成指定的用戶返回值類型 * * @param type * @param jsonData * @return * @throws JSONException */ public static <T> T parseHttpResult(TypeInfo type, String jsonData) throws JSONException { // 處理Void類型的返回值 if (Void.class.isAssignableFrom(type.getComponentType())) { return null; } //獲取當前type的數據類型 Class<?> rawType = type.getRawType(); //是不是Array boolean isArray = rawType != null && Array.class.isAssignableFrom(rawType); //是不是Collection boolean isCollection = rawType != null && Collection.class.isAssignableFrom(rawType); //是不是Map boolean isMap = rawType != null && Map.class.isAssignableFrom(rawType); //獲取泛型類型 Class<?> componentType = type.getComponentType(); //聲明結果對象 T result = null; if (isCollection) {//處理collection result = (T) JSON.parseArray(jsonData, componentType); } else if (isArray) {//處理array result = (T) JSON.parseArray(jsonData, componentType).toArray(); } else if (isMap) {//處理Map result = (T) JSONObject.parseObject(jsonData, type.getType()); } else if (componentType.isAssignableFrom(String.class)) {//處理字符串返回值 return (T) jsonData; } else { // 接口的返回類型若是是簡單類型,則會封裝成爲一個json對象,真正的對象存儲在value屬性上 if (isPrimitiveOrWrapper(componentType)) { result = (T) parseObject(jsonData); } else { //處理自定義對象 result = (T) parseObject(jsonData, componentType); } } return result; } /** * 判斷是不是基本數據類型 * * @param clazz * @return */ public static boolean isPrimitiveOrWrapper(Class clazz) { return (clazz.isPrimitive() || isPrimitiveWrapper(clazz)); } /** * 判斷是不是基本數據類型 * * @param clazz * @return */ public static boolean isPrimitiveWrapper(Class clazz) { return primitiveWrapperTypeMap.containsKey(clazz); } }
TypeInfo typeInfo = ReqClassUtils.getCallbackGenericType(callBack.getClass());
callBack.onReqSuccess(ReqJsonUtils.parseHttpResult(typeInfo, jsonData));
HashMap<String, String> paramsMap = new HashMap<>(); paramsMap.put("sourceType", "2"); paramsMap.put("sourceDesc", "[Android]" + Build.VERSION.RELEASE + "[Mobel]" + Build.BRAND + " " + Build.MODEL + Build.DEVICE); HashMap<String, String> params = dealStringBody(paramsMap); RequestManager.getInstance(this).requestAsyn("xxx/actionUrl", RequestManager.TYPE_POST_JSON, params, new ReqCallBack<String>() { @Override public void onReqSuccess(String result) { request_tv.setText(result); } @Override public void onReqFailed(String errorMsg) { } });
new ReqCallBack<List<Object>>();//集合collection new ReqCallBack<Map<String, User>>();//map new ReqCallBack<Void>();//Void new ReqCallBack<Long>();//基礎類型
小結:如此一來發送請求到解析數據變得So easy !用流行的一句廣告語來講的話,那就是老闆不再用擔憂我搞不定網絡請求和json解析了。緩存