Android [intermediate tutorial] Chapter 8 JSON Data Processing

Source: Internet
Author: User

After a few chapters, I believe that you are ready to parse XML, but today we want to parse JSON data because JSON data occupies a small amount of data, therefore, the main data communication in Android is still based on JSON, and JSON data can interact with Android Ajax, which is quite convenient. Well, let's not talk about it. See the figure and code:

First:

JSON data is defined first:

{"Persons": [{"ID": "1", "status": "", "name": "Sun Wukong", "tool": "", "Number": "killed 50 monsters" },{ "ID": "2", "status": "", "name":" ", "tool": "Nine teeth dingke", "Number": "43 monsters killed" },{ "ID": "3", "status ": "Three younger siblings", "name": "Sha Monk", "tool": "Demon master pin", "Number": "33 monsters killed"}]}

The next step is to define JavaBean. For Java Development, JavaBean can easily store and manage data.

public class Person{private String id;private String status;private String name;private String tool;private String number;public String getId(){return id;}public void setId(String id){this.id = id;}public String getStatus(){return status;}public void setStatus(String status){this.status = status;}public String getName(){return name;}public void setName(String name){this.name = name;}public String getTool(){return tool;}public void setTool(String tool){this.tool = tool;}public String getNumber(){return number;}public void setNumber(String number){this.number = number;}@Overridepublic String toString(){return "Person [id=" + id + ", status=" + status + ", name=" + name+ ", tool=" + tool + ", number=" + number + "]";}}

 

The next step is JSON processing. A jsonhandler class is defined.

Import Java. io. bufferedreader; import Java. io. inputstream; import Java. io. inputstreamreader; import Java. util. arraylist; import Java. util. list; import Org. JSON. jsonarray; import Org. JSON. jsonobject; public class jsonhandler {private inputstream input; private list <person> persons; private person; Public jsonhandler () {} public jsonhandler (inputstream input) {This. input = input;} public void setinput (inputs Tream input) {This. input = input;} public list <person> getpersons () {persons = new arraylist <person> (); try {// custom method, obtain the string json_str = getjsonstring (input) from the input stream; // use the string to generate the JSON object jsonobject object = new jsonobject (json_str ); // convert the persons data in the JSON object into a JSON array jsonarray array = object. getjsonarray ("persons"); // array length int length = array. length (); For (INT I = 0; I <length; I ++) {// convert each array to a JSON object jsonobject OBJ = Array. getjsonobject (I); person = new person (); person. setid (obj. getstring ("ID"); person. setstatus (obj. getstring ("status"); person. setname (obj. getstring ("name"); person. settool (obj. getstring ("tool"); person. setnumber (obj. getstring ("Number"); persons. add (person);} return persons;} catch (exception e) {e. printstacktrace ();} return NULL;}/*** integrate the data in the input stream into a string ** @ Param input * input stream * @ return * @ throws excep Tion */private string getjsonstring (inputstream input) throws exception {bufferedreader reader = new bufferedreader (New inputstreamreader (input); stringbuilder sb = new stringbuilder (); for (string S = reader. readline (); s! = NULL; S = reader. Readline () {sb. append (s) ;}return sb. tostring ();}}

OK. The data here should be parsed. You can test it through the test class. I prefer to test and perform the next development.

Import Java. io. file; import Java. io. fileinputstream; import Java. util. list; import android. OS. environment; import android. test. androidtestcase; public class handlertest extends androidtestcase {public void testjsongetpersons () {// obtain the file path file sd_files = environment in the current SD directory. getexternalstoragedirectory (); // get persons. path of the XML file. Here I have sdcard/data. jsonstring file_path = sd_files.getname () + file. separator + "data. JSON "; try {fileinputstream FCM = new fileinputstream (new file (file_path); jsonhandler = new jsonhandler (FS); List <person> Persons = jsonhandler. getpersons (); system. out. println (persons);} catch (exception e) {e. printstacktrace ();}}}

Okay, the test is okay, so we will go to the main activity class.

Import Java. io. file; import Java. io. fileinputstream; import Java. util. arraylist; import Java. util. hashmap; import Java. util. list; import Java. util. map; import android. app. activity; import android. OS. bundle; import android. OS. environment; import android. widget. listview; import android. widget. simpleadapter; public class jsonactivity extends activity {private listview; private simpleadapter adapter; @ overrideprotected void oncreate (bundle savedinstancestate) {// todo auto-generated method stubsuper. oncreate (savedinstancestate); setcontentview (R. layout. xml_handler); listview = (listview) findviewbyid (R. id. xml_list); try {// getadapter ();} catch (exception e) {e. printstacktrace ();} listview. setadapter (adapter);} private void getadapter () throws exception {list <Map <string, string> lists = new arraylist <Map <string, string> (); // obtain the SD card directory file sd_files = environment. getexternalstoragedirectory (); // obtain the file path string file_path = sd_files.getname () + file. separator + "data. JSON "; // JSON processing fileinputstream FCM = new fileinputstream (new file (file_path); jsonhandler = new jsonhandler (AIS); List <person> Persons = jsonhandler. getpersons (); // convert the data in persons to arraylist <Map <string, string> medium // string>, because simpleadapter uses this type of data to adapt Map <string, string> map; For (person P: Persons) {map = new hashmap <string, string> (); map. put ("ID", p. GETID (); map. put ("status", p. getstatus (); map. put ("name", p. getname (); map. put ("tool", p. gettool (); map. put ("Number", p. getnumber (); lists. add (MAP) ;}// keystring [] From = {"ID", "status", "name", "tool", in hashmap <string, string> ", "Number"}; // idint [] to = {R. id. item_id, R. id. item_status, R. id. item_name, R. id. item_tool, R. id. item_number}; adapter = new simpleadapter (this, lists, R. layout. handler_list_item, from, );}}

Here we also define several layout items, which can be sent together:

Xml_handler.xml

<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: Orientation = "vertical" Android: layout_width = "match_parent" Android: layout_height = "match_parent"> <textview Android: textappearance = "? Android: ATTR/textappearancemedium "Android: layout_width =" wrap_content "Android: text =" three younger siblings of Tang Seng "Android: layout_height =" wrap_content "Android: id = "@ + ID/textview1" Android: paddingleft = "10dip" Android: paddingbottom = "10dip"> </textview> <listview Android: id = "@ + ID/xml_list" Android: layout_height = "wrap_content" Android: layout_width = "match_parent"> </listview> </linearlayout>

Handler_list_item.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="match_parent"android:layout_height="match_parent" android:paddingLeft="10dip"android:paddingRight="10dip"><LinearLayout android:id="@+id/linearLayout1"android:layout_height="wrap_content" android:layout_width="match_parent"><TextView android:textAppearance="?android:attr/textAppearanceMedium"android:layout_width="wrap_content" android:text="TextView"android:layout_height="wrap_content" android:id="@+id/item_id" android:paddingRight="30dip"></TextView><TextView android:textAppearance="?android:attr/textAppearanceMedium"android:layout_width="wrap_content" android:text="TextView"android:layout_height="wrap_content" android:id="@+id/item_status" android:paddingRight="30dip"></TextView><TextView android:textAppearance="?android:attr/textAppearanceMedium"android:layout_width="wrap_content" android:text="TextView"android:layout_height="wrap_content" android:id="@+id/item_name"></TextView></LinearLayout><LinearLayout android:id="@+id/linearLayout2"android:layout_height="wrap_content" android:layout_width="match_parent"><TextView android:textAppearance="?android:attr/textAppearanceMedium"android:layout_width="wrap_content" android:text="TextView"android:layout_height="wrap_content" android:id="@+id/item_tool" android:paddingRight="30dip"></TextView><TextView android:textAppearance="?android:attr/textAppearanceMedium"android:layout_width="wrap_content" android:text="TextView"android:layout_height="wrap_content" android:id="@+id/item_number"></TextView></LinearLayout></LinearLayout>

Now, we have finished processing JSON data.

Source code download
 

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.