/** * http返回解析包 * Created by caizhigui * 2016/11/30. */ public class PlugHttpRes<T> implements Serializable { static public int HTTP_DO_SUCCEED =0; //操作成功 static public int HTTP_DO_ERR_RELATION_MANAGER =1; //操作失败,请联系管理员. static public int HTTP_DO_ERR_PARA_FORMAT =2; //参数值格式有误. static public int HTTP_DO_ERR_RESOUCE =3; //参数值格式有误. static public int HTTP_DO_ERR_AUTHORIZAITON =11; //参数值格式有误. static public int HTTP_DO_ERR_COUSTOM =99; //自定义异常消息 int Code;//"异常编号0为正常,非0错误" String ErrorDesc; //"异常消息" T Result;//"返回结果" public PlugHttpRes() { } public PlugHttpRes(int code, String errorDesc, T result) { Code = code; ErrorDesc = errorDesc; Result = result; } public Type getResultClass() { Type type = new TypeToken<PlugHttpRes<T>>() { }.getType(); return type; } public Type getResultClass2() { Type type = new TypeToken<PlugHttpRes<T>>() { }.getType(); return type; } public int getCode() { return Code; } public void setCode(int code) { Code = code; } public String getErrorDesc() { return ErrorDesc; } public void setErrorDesc(String errorDesc) { ErrorDesc = errorDesc; } public T getResult() { return Result; } public void setResult(T result) { Result = result; } @Override public String toString() { Gson gson=new Gson(); return PlugHttpRes.class.getSimpleName()+":"+gson.toJson(this); } // /** // * 泛型解包到实体变量或数组变量 // * @param json // * @return // */ // public T unpackPlugResToBean(String json) { // T t =null; // Type type = new TypeToken<T>() { // }.getType(); // PlugHttpRes<T> plugHttpRes = new Gson().fromJson(json, type); // if (plugHttpRes.getCode() == PlugHttpRes.HTTP_DO_SUCCEED){ // t = plugHttpRes.getResult(); // if (t!=null){ // } // }else { // Log.i("Login","登录发生错误"+plugHttpRes.getCode()); // } // return t; // }}
===========调用例子=========
private EnvironmentalParameters unpackPlugResToBean(String json) { EnvironmentalParameters environmentalParameters =null; Type type = new TypeToken<PlugHttpRes<EnvironmentalParameters>>() { }.getType(); PlugHttpRes<EnvironmentalParameters> pluginhttpRes = new Gson().fromJson(json, type); if (pluginhttpRes.getCode() == PlugHttpRes.HTTP_DO_SUCCEED){ environmentalParameters = pluginhttpRes.getResult(); if (environmentalParameters!=null){ Log.i(TAG,"解包成功:"+environmentalParameters.WeChatID); } }else { Log.i("Login","登录发生错误"+pluginhttpRes.getCode()); } return environmentalParameters; }
使用Gson解析json到任意类型的Bean
最新推荐文章于 2022-04-21 14:35:26 发布