[Android] Create an android-generic JSON data parsing framework

Source: Internet
Author: User
Tags int size

The most common use of Android and iOS applications for web interaction is the JSON data protocol, which is a brisk feature of the mobile platform, and is a gradual replacement for XML, with the following two popular JSON formats:

{"
	code": "10000",
	"message": "Login OK",
	"result": {
		"User": {
			"id": 1,
			"name": "James",
			' sign ': ' Just do It '}}}
{'
	code ': ' 10000 ',
	' message ': ' Get Weibo list ok ',
	' result ': {
		' weibo.list ': [
			{
				' id ': 2 ,
				"Author": "Zhuge", "
				content": "Weibo content 2"
			},
			{
				"id": 1,
				"author": "Zhuge",
				"Content": "Weibo content 1"}}}

The structure of the two formats is consistent, the only difference is the result field, the former result field is a jsonobject, often used to return some ordinary information, the latter is Jsonarray, long with the return of some list data.

First of all, the most conventional most common analytic way, define two entities, a call user, a call Weibo, please Islands sweep.

Package com.zhuge.jsonparse;
Import java.util.ArrayList;

Import Java.util.HashMap;
Import Org.json.JSONArray;
Import org.json.JSONException;


Import Org.json.JSONObject;
	public class User extends Basemodel {private String ID;
	private String name;

	Private String sign;
	Public String GetId () {return id;
	public void SetId (String id) {this.id = ID;
	Public String GetName () {return name;
	public void SetName (String name) {this.name = name;
	Public String getsign () {return sign;
	} public void Setsign (String sign) {this.sign = sign;
	@Override public String toString () {return "User [id= + ID +", name= "+ name +", sign= "+ sign +]"; public static hashmap<string, object> Parseuserinfo (String jsonstr) {hashmap<string, object> result =
		New hashmap<string, object> ();
		User user = new user ();
			try {jsonobject Apijson = new Jsonobject (JSONSTR);
			Result.put ("Code", Apijson.getstring ("Code")); Result.put ("Message", apijson.getstring ("message"));
			Jsonobject Resultjson = apijson.getjsonobject ("result"). Getjsonobject ("User");
			User.setid (resultjson.getstring ("id"));
			User.setname (resultjson.getstring ("name"));
			User.setsign (resultjson.getstring ("sign"));
		Result.put ("result", user);
		catch (Jsonexception e) {e.printstacktrace ();
	return result; }

}
Package com.zhuge.jsonparse;
Import java.util.ArrayList;

Import Java.util.HashMap;
Import Org.json.JSONArray;
Import org.json.JSONException;


Import Org.json.JSONObject;
	public class Weibo extends Basemodel {private String ID;
	Private String author;

	Private String content;
	Public String GetId () {return id;
	public void SetId (String id) {this.id = ID;
	Public String Getauthor () {return author;
	} public void Setauthor (String author) {this.author = author;
	Public String getcontent () {return content;
	public void SetContent (String content) {this.content = content;  @Override public String toString () {return "Weibo [id= + ID +", author= "+ author +", content= "+ content +
	"]";  public static hashmap<string, object> parseweibolist (String jsonstr) {hashmap<string, object> result =
		New hashmap<string, object> ();
		arraylist<weibo> Lstweibo = new arraylist<weibo> (); try {jsonobject Apijson = new Jsonobject (JSONSTR);
			Result.put ("Code", Apijson.getstring ("Code"));
			Result.put ("Message", apijson.getstring ("message"));
			Jsonobject Resultjson = apijson.getjsonobject ("result");
			Jsonarray resultarray = Resultjson.getjsonarray ("Weibo.list");
				for (int i = 0; i < resultarray.length (); i++) {Jsonobject Weibojson = Resultarray.getjsonobject (i);
				Weibo Weibo = new Weibo ();
				Weibo.setid (weibojson.getstring ("id"));
				Weibo.setauthor (weibojson.getstring ("author"));
				Weibo.setcontent (weibojson.getstring ("content"));
			Lstweibo.add (Weibo);
		} result.put ("Result", Lstweibo);
		catch (Jsonexception e) {e.printstacktrace ();
	return result; }

}

All two entities inherit from Basemodel, and Basemodel is just an empty class, which has no definition of anything, though it is an empty class, but it must also be inherited to prepare for the versatility behind us. The user and Weibo two entity classes define three simple properties, then some automatically generated get and set methods, and finally the static method of parsing and data encapsulation of JSON data. This kind of resolution is not very versatile, each definition of an entity class to be resolved separately, this is obviously not the way we want, as a program apes will not "lazy" that can only work overtime.

OK, let's take a look at the focus of this article to create a common JSON data parsing framework, as long as the data format defined by the JSON protocol above (you can also modify the code in your own format), simply fix all the entity class parsing:

Package com.zhuge.jsonparse;
Import Java.lang.reflect.Field;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import Java.util.Iterator;

Import Java.util.Map;
Import Org.json.JSONArray;
Import org.json.JSONException;


Import Org.json.JSONObject;

Import Android.util.Log;
	/** * JSON Universal parsing Framework * @author Zhugeheng * */public class Apiresult {private String code;
	Private String message;
	Private map<string, basemodel> Resultmap; Private map<string, arraylist<?
	
	Extends basemodel>> resultlist;
		Public Apiresult () {this.resultmap = new hashmap<string, basemodel> (); This.resultlist = new hashmap<string, arraylist<?
	Extends Basemodel>> ();
	Public String GetCode () {return this.code;
	public void Setcode (String code) {this.code = code;
	Public String GetMessage () {return this.message;
	public void Setmessage (String message) {this.message = message;
	/** * Get Object Entity * @param modelname * @return * @throws Exception */Public Object Getmodel (String modelname) throws Exception {Object model = this.resultMap.ge
		T (modelname);
		if (model = = NULL) {throw new Exception ("Result map is empty");
	return model; /** * Get Object Entity list * @param modelname * @return * @throws Exception * * public arraylist<? Extends Basemodel> getmodellist (String modelname) throws Exception {arraylist<? extends basemodel>
		= This.resultList.get (modelname);
		if (modellist = = NULL | | modellist.size () = 0) {throw new Exception ("Result list is empty");
	return modellist;  /** * Get apiresult entity * @param jsonstr * @return * @throws Exception/public apiresult Getapiresult (String
		JSONSTR) throws Exception {Apiresult Apiresult = new Apiresult ();
		Jsonobject jsonobject = null;
			try {jsonobject = new Jsonobject (JSONSTR);
				if (jsonobject!= null) {Apiresult.setcode (jsonobject.getstring ("Code")); Apiresult.setmessage (jsonobjEct.getstring ("message"));
			Apiresult.setresult (jsonobject.getstring ("result"));
		The catch (Jsonexception e) {throw new Exception ("Json format error");
		catch (Exception e) {e.printstacktrace ();
	return apiresult; /** * Resolves the contents of the result field * @param result * @throws Exception/@SuppressWarnings ("unchecked") private void Setr Esult (String result) throws Exception {if (result.length () > 0) {jsonobject jsonobject = new Jsonobject (Result)
			;
			Iterator<string> it = Jsonobject.keys ();
				while (It.hasnext ()) {String Jsonkey = It.next ();
				String modelname = Getmodelname (Jsonkey);
				The entity class is in the absolute path (package name + class name) String Modelclassname = "Com.zhuge.jsonparse.model." + modelname;
				LOG.D ("Apiresult", "JSON key:" + Jsonkey + ", Model class Name:" + modelclassname);
				The default array processing Jsonarray Modeljsonarray = Jsonobject.optjsonarray (Jsonkey); if (Modeljsonarray = = null) {//not array, then it is an ordinary object, such as the user class Jsonobject Modeljsonobject = Jsonobject.optjsonobject (Jsonkey);
					if (Modeljsonobject = = null) {throw new Exception ("JSON result is invalid");
				///Convert Jsonobject to model class and save results to map This.resultMap.put (modelname, Json2model (Modelclassname, modeljsonobject));
					else {//is array, such as Weibo class arraylist<basemodel> modellist = new arraylist<basemodel> (); 
						for (int i = 0; i < modeljsonarray.length (); i++) {Jsonobject modeljsonobject = Modeljsonarray.optjsonobject (i);
					Converts the jsonobject to the model class and adds it to the list Modellist.add (Json2model (Modelclassname, modeljsonobject));
				///Add the results list to the map this.resultList.put (modelname, modellist); /** * Converts a JSON object to an Entity object * @param modelclassname entity class is in the absolute path (package name + class name), case sensitive * @param modeljsonobject "Resul The contents of the T field * @return * @throws Exception * * @SuppressWarnings ("unchecked") Private Basemodel Json2model (String mode Lclassname, Jsonobject modeljsonobject) throws Exception {Basemodel modeLobj = (Basemodel) class.forname (modelclassname). newinstance (); Get entity class Class<?
		Extends basemodel> Modelclass = Modelobj.getclass ();
		Gets all the property collections for the entity class iterator<string> it = Modeljsonobject.keys ();
			while (It.hasnext ()) {//property name String Varfield = It.next ();
			Parse attribute value String varvalue = modeljsonobject.getstring (Varfield);
			LOG.D ("Apiresult", "field:" + Varfield + "value:" + varvalue);
			The Build property encapsulates the object field field = Modelclass.getdeclaredfield (Varfield);
			Sets the accessible private property field.setaccessible (True);
		The value of the field attribute of the Modelobj object is set to the parsed value Field.set (Modelobj, varvalue);
	return modelobj;  /** * Remove the return result "list" * @param str * @return/private string Getmodelname (String str) {string[] Strarr =
		Str.split ("\\w");
		if (Strarr.length > 0) {str = strarr[0];
	return str; }
	
}
Please focus on SetresultAnd Json2modelmethod, and the GetMode method is used to get an ordinary entity object, such as the User,getmodelist method, to obtain a list of entity objects such as weibolist, which are exposed externally. Critical code has detailed comments, better understanding, here is no longer verbose. Then you can kill the Parsexxx method in the user and Weibo classes, and then see how to invoke our common method:
Package com.zhuge.jsonparse;
Import java.io.IOException;
Import Java.io.InputStream;

Import java.util.ArrayList;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.view.View.OnClickListener;


Import Android.widget.TextView; public class Mainactivity extends activity {@Override protected void onCreate (Bundle savedinstancestate) {Super.onc
		Reate (savedinstancestate);
		
		Setcontentview (R.layout.activity_main);
		
		Final TextView Tvresult = (TextView) Findviewbyid (R.id.tv_result); 
				Findviewbyid (r.id.btn_obj). Setonclicklistener (New Onclicklistener () {@Override public void OnClick (View arg0) {
				String jsonstr = Readassetsfile ("User.json"); try {//hashmap<string, object> result = User.parseuserinfo (JSONSTR);//user user = (user) Result.get ("ResU
					LT ");
					Apiresult result = new Apiresult (). Getapiresult (JSONSTR);
					User user = (user) Result.getmodel ("User");
				Tvresult.settext (User.tostring ());catch (Exception e) {e.printstacktrace ();
		
		}
			}
		}); 
			Findviewbyid (R.id.btn_array). Setonclicklistener (New Onclicklistener () {@SuppressWarnings ("unchecked") @Override
				public void OnClick (View arg0) {String jsonstr = readassetsfile ("Weibo.json"); try {//hashmap<string, object> result = Weibo.parseweibolist (JSONSTR);//Arraylist<weibo> LstWeibo
					= (arraylist<weibo>) result.get ("result");
					Apiresult result = new Apiresult (). Getapiresult (JSONSTR);
					Arraylist<weibo> Lstweibo = (arraylist<weibo>) result.getmodellist ("Weibo");
					String str = "";
					for (Weibo weibo:lstweibo) {str = weibo.tostring () + "\ n";
				} tvresult.settext (str);
				catch (Exception e) {e.printstacktrace ();
	}
			}
		}); /** * Read the contents of the Assets folder (test JSON string) * @param filename * @return/private string Readassetsfile (String fileName
			{try {InputStream is = Getassets (). open (FileName); INT size = is.available ();
			byte[] buffer = new Byte[size];
			Is.read (buffer);

			Is.close ();
			string result = new String (buffer, "UTF-8");
		return result;
			catch (IOException e) {e.printstacktrace ();
		return null;
 }
	}
}
The activity is very simple, there are two button, the first click after parsing user, the second click after the resolution Weibo List, and then in TextView entity with the ToString method to print out. In addition, our JSON data is typically obtained from a Web server, and this example provides a convenient place for the JSON file to be placed in the assets folder and read directly (network access data is not the focus of this article). OK, a more versatile analytic framework is done, and then you can goodbye with the physical say of parsing JSON data.

Respect original, reprint please indicate source: http://blog.csdn.net/zhugehengheng/article/details/45250553

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.