Android data loading and Json parsing-Framework Version
Method call
New ApiUser (this). initData (new ApiRequest () {@ Override public void onResult (BeanRequest bean) {// if the interface call fails, the prompt if (! Bean. isSuccess () {UtilToast. show (Activitymain. this, bean. getErrInfo (), UtilToast. STYLE_ERROR);} // Json data parsing: BeanInitData data entity class BeanInitData data = (BeanInitData) ApiPublic. readJson (JSONObject) bean. getData (), BeanInitData. class );}});
Next is the method process:
1. Create an object class:
public class BeanInitData { private int jobApplicantCount;//":33," private int employJobCount;//":21," private int enterpriseCount;//":14," private ArrayList
ads; public int getJobApplicantCount() { return jobApplicantCount; } public void setJobApplicantCount(int jobApplicantCount) { this.jobApplicantCount = jobApplicantCount; } public int getEmployJobCount() { return employJobCount; } public void setEmployJobCount(int employJobCount) { this.employJobCount = employJobCount; } public int getEnterpriseCount() { return enterpriseCount; } public void setEnterpriseCount(int enterpriseCount) { this.enterpriseCount = enterpriseCount; } public ArrayList
getAds() { return ads; } public void setAds(ArrayList
ads) { this.ads = ads; }}
2. All interface calls should be written together,
Public class ApiUser {private Context ctx; public ApiUser (Context ctx) {this. ctx = ctx;} public void initData (ApiRequest request) {// ApiPublic. SERERIP is the interface url String url = ApiPublic. SERERIP + "initData. json "; HttpParam param = new HttpParam (); ApiPublic. startHttpPost (ctx, url, param, request);} // login // parameter String account, String password, String loginFrom public void login (String account, String password, String loginFrom, apiRequest request) {String url = ApiPublic. SERERIP + "login.html"; HttpParam param = new HttpParam (); param. addParams ("account", account); param. addParams ("password", password); param. addParams ("loginFrom", loginFrom); ApiPublic. startHttpPost (ctx, url, param, request );}}
3. ApiPublic includes pagination and Json parsing without pagination
Public class ApiPublic {
Public final static String SERERIP = "http://write.blog.csdn.net/mdeditor/api/";/*** start to call the interface: POST method * @ param url * @ param request */public static void startHttpPost (Context ctx, String url, HttpParam param, ApiRequest request) {HttpRequest http = new HttpRequest (url, param, 0, request); http.exe cute ();} public static void startHttpPost (String url, HttpParam param, ApiRequest request) {HttpRequest http = new HttpRequest (url, param, 0, request); http.exe cute ();}/*** start to call the interface: POST method, transfer File * @ param url * @ param request */public static void startHttpPostFile (Context ctx, String url, HttpParam param, ApiRequest request) {HttpRequest http = new HttpRequest (url, param, 1, request); http.exe cute ();} public static void startHttpPostFile (String url, HttpParam param, ApiReq Uest request) {HttpRequest http = new HttpRequest (url, param, 1, request); http.exe cute () ;}/ *** cancel interface call */public static void httpTaskCancel () {HttpRequest http = new HttpRequest (); http. onCancelled ();}/*** common JSON parsing ** @ param result input JSON String * @ return String success return "", error Description */public static BeanRequest readJsonUtil (String result) {if (TextUtils. isEmpty (result) {return new BeanRequest (). set Error ("no response data");} try {JSONObject jsonObject = new JSONObject (result); if (jsonObject. isNull ("status") {return new BeanRequest (). setError ("failed to accept");} // 0 success, 1 error, 2 exception int Status = jsonObject. getInt ("status"); if (Status! = 0) {String description = jsonObject. getString ("desc"); return new BeanRequest (). setError (description);} BeanRequest bean = new BeanRequest (); bean. setSuccess (true); bean. setResult (result); bean. setData (jsonObject. isNull ("data ")? Null: jsonObject. get ("data"); return bean;} catch (JSONException e) {e. printStackTrace (); return new BeanRequest (). setError ("Data Exception");}/*** parse the JSON object without paging ** @ param result json data * @ param entityClass entity class * @ return */public static
Object readJson (final JSONObject result, Class
EntityClass) {if (null = result) return null; return new Gson (). fromJson (result. toString (), entityClass);}/*** parses the JSON array, including the paging * Data example: {"total": xx, "rows ": []} * @ param result json data * @ param entityClass entity class * @ return */public static
List readJsonListPage (final JSONObject result, BeanPage page, Class
EntityClass) {if (null = result) return null; try {int total = result. getInt ("total"); page. setTotal (total); JSONArray array = result. getJSONArray ("rows"); List
List = new ArrayList
(); Gson gson = new Gson (); int size = array. length (); for (int I = 0; I <size; I ++) {list. add (gson. fromJson (array. getString (I), entityClass);} return list;} catch (JSONException e) {return null ;}/ *** parses the JSON array, does not include paging ** @ param result json data * @ param entityClass entity class * @ return */public static
List readJsonList (final JSONArray result, Class
EntityClass) {if (null = result) return null; List
List = new ArrayList
(); Gson gson = new Gson (); try {int size = result. length (); for (int I = 0; I <size; I ++) {list. add (gson. fromJson (result. getString (I), entityClass) ;}} catch (JSONException e) {} return list ;} /*** form a simple json * @ param id * @ param name * @ return */public static JSONObject writeJsonSimple (int id, String name) {JSONObject json = new JSONObject (); try {json. put ("id", id); json. put ("name", name);} catch (JSONException e) {e. printStackTrace ();} return json;} public static JSONObject writeJson (int extendId, String tagValue, String tagText) {JSONObject json = new JSONObject (); try {json. put ("extendId", extendId); json. put ("tagValue", tagValue); json. put ("tagText", tagText);} catch (JSONException e) {e. printStackTrace ();} return json;
}
4. Data Loading AsyncTask
Public class HttpRequest extends AsyncTask
{Private HttpParam params; private String url = null; private ApiRequest mCallBack = null; private String result = null; private String errInfo = null;/*** // form method: * 0: application/x-www-form-urlencoded * 1: multipart/form-data * 2: multipart/form-data. The attachment ContentType is set to "image/jpeg ", file name */private int _ formFlag = 0; public HttpRequest () {}/ *** constructor * @ param url: the URL called by the param url * @ param parameter * @ param fo RmFlag form: 0: application/x-www-form-urlencoded, 1: multipart/form-data * @ param request interface callback */public HttpRequest (String url, HttpParam param, int formFlag, ApiRequest request) {this. url = url; this. mCallBack = request; this. params = param; this. _ formFlag = formFlag; this. result = ""; this. errInfo = "";}/*** execute POST call */private void runReqPost () {try {HttpParams httpParams = new basichttpsr Ams (); HttpConnectionParams. setConnectionTimeout (httpParams, 8000); HttpClient httpClient = new DefaultHttpClient (httpParams); HttpPost httpPost = new HttpPost (url); if (_ formFlag = 0) httpPost. setEntity (params. getParamsPost (); else if (_ formFlag = 1) {httpPost. setEntity (params. getParamsPostFile (); // when uploading an attachment, put the parameter in the header !!! Map
Headers = params. getParams (); if (null! = Headers &&! Headers. isEmpty () {for (Map. Entry
Entry: headers. entrySet () {String key = entry. getKey (); Object values = entry. getValue (); if (values instanceof String) {httpPost. addHeader (key, (String) values) ;}}} HttpResponse httpResponse = httpClient.exe cute (httpPost); int code = httpResponse. getStatusLine (). getStatusCode (); Log. I ("getStatusCode ()", "------->" + code); if (code = HttpStatus. SC _ OK) {result = EntityUtils. toString (http Response. getEntity (), HTTP. UTF_8);} else {errInfo = "network error";} catch (ClientProtocolException e) {e. printStackTrace (); errInfo = "client protocol exception";} catch (IOException e) {e. printStackTrace (); errInfo = "unable to connect to the server";}/*** AsyncTask method overload pre-execution */@ Override protected void onPreExecute () {super. onPreExecute ();}/*** AsyncTask method overload background asynchronous execution * @ return */@ Override protected Void doInBackground (Void... pa Rams) {try {this. runReqPost ();} catch (Exception e) {e. printStackTrace (); errInfo = "interface exception";} return null;}/*** callback when the AsyncTask method is reloaded successfully */@ Override protected void onPostExecute (Void voids) {if (null = mCallBack | (null! = ErrInfo &&! ErrInfo. equals ("") {Log. e ("info", "failed ---> errInfo:" + errInfo); mCallBack. onResult (new BeanRequest (). setError (errInfo); return;} BeanRequest bean = ApiPublic. readJsonUtil (result); if (! Bean. isSuccess () Log. w ("info", "failed --->" + result); else Log. v ("info", "success --->" + result); mCallBack. onResult (bean);}/*** AsyncTask method overload callback when the task is successfully canceled */@ Override protected void onCancelled () {if (mCallBack! = Null) {Log. w ("info", "failed ---> task canceled"); mCallBack. onResult (new BeanRequest (). setError ("canceled "));}}}
5. object classes of parameters returned by interface calls
Public class BeanRequest {private boolean success = true; // whether the interface call is successful private String errInfo; // The error cause is private Object Data; // The service Data is obtained successfully, and the business Data is private String result; // public BeanRequest setError (String errInfo) {this. success = false; this. errInfo = errInfo; return this;} public BeanRequest setSucc (String result) {this. success = true; this. result = result; return this;} public boolean isSuccess () {return success;} public void setSuccess (boolean success) {this. success = success;} public String getErrInfo () {return errInfo;} public void setErrInfo (String errInfo) {this. errInfo = errInfo;} public Object getData () {return Data;} public void setData (Object data) {Data = data;} public String getResult () {return result ;} public void setResult (String result) {this. result = result ;}}
6. Storage of network Request Parameters
/*** Network Request Parameter Storage class, which is stored by Map */public class HttpParam {private Map
Params = new HashMap
(); Public Map
GetParams () {return params;} public void setParams (Map
Params) {this. params = params;}/*** common parameter * @ param key * @ param values */public void addParams (String key, Object values) {this. params. put (key, values);}/*** parameters with attachments. Only one attachment is passed * @ param key * @ param values */public void addParams (String key, file values) {this. params. put (key, values);}/*** parameters with attachments. Multiple attachments are uploaded * @ param key * @ param values */public void addParams (String key, Set
Values) {this. params. put (key, values);}/*** when calling the Post method, retrieve the parameter * @ return * @ throws UnsupportedEncodingException */public HttpEntity getParamsPostFile () throws UnsupportedEncodingException {MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder. create (); if (null = params | params. isEmpty () {return multipartEntityBuilder. build () ;}for (Map. entry
Entry: params. entrySet () {String key = entry. getKey (); Object values = entry. getValue (); if (values instanceof File) {multipartEntityBuilder. addBinaryBody (key, (File) values);} else if (values instanceof Set) {for (File file: (Set
) Values) {multipartEntityBuilder. addBinaryBody (key, (File) file) ;}} return multipartEntityBuilder. build ();}/*** use the application/x-www-form-urlencoded form to pass the parameter * @ return */public HttpEntity getParamsPost () {List
NameValuePairs = new ArrayList
(); JSONObject jsonObj = new JSONObject (); try {for (Map. Entry
Entry: params. entrySet () {String key = entry. getKey (); Object values = entry. getValue (); if (values instanceof JSONArray) {jsonObj. put (key, (JSONArray) values);} else {jsonObj. put (key, values) ;}} catch (JSONException e) {e. printStackTrace ();} nameValuePairs. add (new BasicNameValuePair ("param", jsonObj. toString (); Log. I ("wocaonima", "parameter value:" + jsonObj); HttpEntity entity = null; try {entity = new UrlEncodedFormEntity (nameValuePairs, HTTP. UTF_8);} catch (UnsupportedEncodingException e) {e. printStackTrace () ;}return entity ;}}