Android parsing Jsonobject and Jsonarray comparison

Source: Internet
Author: User

During the interaction between the Android client and the server, the client typically uses JSON to parse the server's return data. There are two kinds of data formats at this time. But it's all a string or string array!

1, Jsonobject

Here is the PHP side code:

<? PHP $array Array (  ' username ' = ' lhh ',  ' password ' = ' 123456 ',  ' user_id ' = ' 1 '); echo json_encode ($array);? >

Here we are just simulations, so, in the absence of a server, it can also be defined in Java code, as follows:

String Strjson = "{" username ":" lhh "," Password ":" 123456 "," user_id ":" 1 "}";

Here's the Android code:

By do not shave a Hugh elder brother 2014//11/15package Com.example.jsonjs;import Java.io.bufferedreader;import Java.io.InputStreamReader; Import Org.apache.http.httpresponse;import Org.apache.http.client.httpclient;import Org.apache.http.client.methods.httpget;import Org.apache.http.impl.client.defaulthttpclient;import Org.json.jsonobject;import Android.app.activity;import Android.os.bundle;import Android.os.Looper;import Android.util.log;import Android.view.menu;import Android.view.menuitem;import Android.widget.TextView;import Android.widget.toast;public class Mainactivity extends Activity {@Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); new Thread (New Runnable () {@Overridepublic void run () {Looper.prepare ();TODO auto-generated method Stubhttpclient client = new Defaulthttpclient (); StringBuilder builder = new StringBuilder ();//Address according to the actual situation httpget Myget = new HttpGet ("http://192.168.1.104/login.php");try {httpresponse response = Client.execute (Myget);        BufferedReader reader = new BufferedReader (New InputStreamReader (Response.getentity (). GetContent ()));        for (String s = reader.readline (); s! = null; s = Reader.readline ()) {builder.append (s); }//Convert to Jsonobject jsonobject jsonobject = new Jsonobject (builder.tostring ());String re_username = jsonobject.getstring ("username");                String Re_password = jsonobject.getstring ("password");        Settitle ("User id_" +re_user_id);        LOG.V ("url response", "true=" +re_username);        LOG.V ("url response", "true=" +re_password);        Tv1.settext (Re_username);        Tv2.settext (Re_password);    Toast.maketext (Getapplicationcontext (), Re_username, Toast.length_long). Show ();       } catch (Exception e) {log.v ("url response", "false");        Toast.maketext (Getapplicationcontext (), "false", Toast.length_long). Show ();    E.printstacktrace (); } looper.loop ();}}). Start ();}}

The code requires the server, if it is a Java-defined JSON data.

2, Jsonarray

Here is the PHP code (I used the database)

<?PHP$link=mysql_connect("localhost", "username", "password");mysql_query("SET NAMES UTF8");mysql_select_db("Test",$link);$sql=mysql_query("SELECT * from Teacher",$link); while($row=Mysql_fetch_assoc($sql))    $output[]=$row;EchoJson_encode ($output);Mysql_close();?>

Of course, you can also follow the above definition in Java code, as follows:

String Strjson = "[{" id ":" 1 "," name ":" Wang "},{" id ":" 2 "," Name ":" Liu "}]";

Here's the Android code:

By do not shave a Hugh elder brother 2014/11/15package Com.example.jsonjsarr;import Java.io.bufferedreader;import java.io.IOException; Import Java.io.inputstreamreader;import Java.nio.charset.charset;import Org.apache.http.httpresponse;import Org.apache.http.client.httpclient;import Org.apache.http.client.methods.httpget;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.impl.conn.tsccm.threadsafeclientconnmanager;import Org.json.jsonarray;import Org.json.jsonexception;import Org.json.jsonobject;import Android.app.activity;import Android.os.Bundle;import Android.os.looper;import Android.util.log;import Android.view.menu;import Android.view.menuitem;import Android.widget.edittext;import Android.widget.toast;public class Mainactivity extends Activity {@Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_ Main); New Thread (New Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stublooper.prepare (); Getserverjsondatawithtypes (); Looper.loop ();}}). Start ();} private void Getserverjsondatawithtypes () {//TODO auto-generated method Stubint res = 0; HttpClient client = new Defaulthttpclient (); StringBuilder str = new StringBuilder ();//Here the address depends on the actual situation httpget HttpGet = new HttpGet ("http://192.168.1.104/login.php");Try{httpresponse httpres = Client.execute (httpget); res = Httpres.getstatusline (). Getstatuscode (); if (res = = 200) { BufferedReader buffer = new BufferedReader (New InputStreamReader (Httpres.getentity (). GetContent ())); String s = buffer.readline (); for (; S!=null;s=buffer.readline ()) {str.append (s);} The string is converted to Jsonarrayjsonarray json = new Jsonarray (str.tostring ()); String strs= ""; for (int i = 0;i<json.length (); i++) {//access by subscriptjsonobject jsonobject = (jsonobject) json.opt (i);STRs + = jsonobject.getstring ("name");} Toast.maketext (Getapplicationcontext (), STRs, Toast.length_long). Show (); Else{toast.maketext (Getapplicationcontext (), "Httperror", Toast.length_long). Show ();}} catch (Exception e) {log.v ("test", "Exception");}}}

  

The two types can be seen, its essence is the same, a jsonarray into multiple jsonobject to operate.

By the way:

1, in Android 4.X, do not put in the main thread for network access, or the app may be forced to quit.

2. Note the difference between a UI thread and a non-UI thread.

3. The role of Looper.prepare () and Looper.loop ().

4. When you need network access, don't forget to add permissions in Mainfest

<uses-permission android:name= "Android.permission.INTERNET"/>

5, little brother, if there is a mistake, please also point out.

6, the code although I wrote, but have a problem try not to find me, is his own long crooked.  

7, reprint please indicate the source.

Android parsing Jsonobject and Jsonarray comparison

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.