A simple example of returning JSON data in the android parsing background !!!

Source: Internet
Author: User

Hello everyone, today I will share with you the example of Android parsing JSON. I have installed Tomcat here to let my computer act as the server. The most important thing is that you can modify the returned results as needed.

First, let's take a look at the definition of JSON and its comparison with XML:

JSON definition:

A lightweight data exchange format with good readability and ease of writing. Mainstream technologies in the industry provide a complete solution (similar to regular expressions and supported by most languages) to exchange data between different platforms. JSON adopts a highly compatible text format and has behaviors similar to the C language system. -Json.org

JSON vs XML

1. The data readability of JSON and XML is basically the same.
2. JSON and XML have the same rich parsing Methods
3. JSON is smaller than XML.
4. easier interaction between JSON and JavaScript
5. JSON is less descriptive than XML.
6. JSON is much faster than XML.

Tomcat installation:

Tomcathttp: // tomcat.apache.org/download and install Tomcat. If the installation is successful, start Tomcat and enter: http: // localhost: 8080/index. jsp in the browser. A tomcat homepage interface is displayed,

In the tomcat installation directory, find webapps \ RootIndex. jsp, create an index2.jsp, use notepad or something, and edit the content as follows:

{STUDENTS: [{Name: 'wei zhulin ', age: 25}, {Name: 'wei', age: 26}], class: 'second class '}

Then, enter http: // localhost: 8080/index2.jsp in the browser to return the following results (This simulates the data returned in the background ):

Create an android project jsondemo.

The project directory is as follows:


Here I encapsulate a jsonutil tool class, the Code is as follows:

Package COM. tutor. jsondemo; import Java. io. ioexception; import Java. io. inputstreamreader; import Java. io. unsupportedencodingexception; import Org. apache. HTTP. httpentity; import Org. apache. HTTP. httpresponse; import Org. apache. HTTP. client. methods. httpget; import Org. apache. HTTP. impl. client. defaulthttpclient; import Org. apache. HTTP. params. basichttpparams; import Org. apache. HTTP. protocol. HTTP; import Org. JSON. JS Onexception; import Org. JSON. jsonobject; import android. util. log;/*** @ author frankiewei. * tool class in JSON format. */public class jsonutil {Private Static final string tag = "jsonutil "; /*** get JSON content * @ Param URL * @ return jsonarray * @ throws jsonexception * @ throws connectionexception */public static jsonobject getjson (string URL) throws jsonexception, exception {return New jsonobject (getrequest (URL ));}/*** Send a GET request to the API and return the information obtained from the background. ** @ Param URL * @ return string */protected static string getrequest (string URL) throws exception {return getrequest (URL, new defaulthttpclient (New basichttpparams ()));} /*** send a GET request to the API and return the information obtained from the background. ** @ Param URL * @ Param client * @ return string */protected static string getrequest (string URL, defaulthttpclient client) throws exception {string result = NULL; int statuscode = 0; httpget getmethod = new httpget (URL); log. D (TAG, "Do the getrequest, url =" + URL + ""); try {// getmethod. setheader ("User-Agent", user_agent); httpresponse = client.exe cute (getmethod); // statuscode == 200 normal statuscode = httpresponse. getstatusline (). getstatuscode (); log. D (TAG, "statuscode =" + statuscode); // process returned httpresponse information result = retrieveinputstream (httpresponse. getentity ();} catch (exception e) {log. E (TAG, E. getmessage (); throw new exception (E);} finally {getmethod. abort ();} return result;}/*** process httpresponse information, return string ** @ Param httpentity * @ return string */protected static string retrieveinputstream (httpentity) {int length = (INT) httpentity. getcontentlength (); // The number of bytes of the content, or a negative number if unknown. if the content length is known but exceeds long. max_value, a negative number is returned. // length =-1. The following error is returned: println needs a messageif (length <0) Length = 10000; stringbuffer = new stringbuffer (length ); try {inputstreamreader = new inputstreamreader (httpentity. getcontent (), HTTP. utf_8); char buffer [] = new char [length]; int count; while (COUNT = inputstreamreader. read (buffer, 0, length-1)> 0) {stringbuffer. append (buffer, 0, count) ;}} catch (unsupportedencodingexception e) {log. E (TAG, E. getmessage ();} catch (illegalstateexception e) {log. E (TAG, E. getmessage ();} catch (ioexception e) {log. E (TAG, E. getmessage ();} return stringbuffer. tostring ();}}

Compile the main activity code jsondemoactivity. The Code is as follows:

Package COM. tutor. jsondemo; import Org. JSON. jsonarray; import Org. JSON. jsonexception; import Org. JSON. jsonobject; import android. app. activity; import android. OS. bundle; import android. widget. textview; public class jsondemoactivity extends activity {/*** background address for access. The local address cannot be accessed using 127.0.0.1. 10.0.2.2 */Private Static final string base_url = "http: // 10.0.2.2: 8080/index2.jsp "; private textview mstudenttextview; private textview mclasstextview; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); setupviews ();}/*** initialization */private void setupviews () {mstudenttextview = (textview) findviewbyid (R. id. student); mclasstextview = (textview) findviewbyid (R. id. classes); try {// obtain the JSON object jsonobject mjsonobject = jsonutil returned by the background. getjson (base_url); // obtain the student array jsonarray mjsonarray = mjsonobject. getjsonarray ("Students"); // get the first student jsonobject firststudent = mjsonarray. getjsonobject (0); // obtain the class string classes = mjsonobject. getstring ("class"); string studentinfo = classes + "Total" + mjsonarray. length () + "student. "+" First Student name: "+ firststudent. getstring ("name") + "Age:" + firststudent. getint ("Age"); mstudenttextview. settext (studentinfo); mclasstextview. settext ("class:" + classes);} catch (jsonexception e) {e. printstacktrace ();} catch (exception e) {e. printstacktrace ();}}}

The layout file main. XML code used here is as follows:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <TextView        android:id="@+id/student"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="@string/hello" />        <TextView         android:id="@+id/classes"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        /></LinearLayout>

Finally, add the network access permission to androidmainfest. xml:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.tutor.jsondemo"    android:versionCode="1"    android:versionName="1.0" >    <uses-permission android:name="android.permission.INTERNET"></uses-permission>    <application        android:icon="@drawable/ic_launcher"        android:label="@string/app_name" >        <activity            android:name=".JSONDemoActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>

Run the project as follows:

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.