Chapter Networking/json Services

Source: Internet
Author: User

<1>json Service

In the previous sections, you learned how to consume XML Web services by using HTTP to connect to the Web server and then O Btain the

Results in XML. Also learned how to use DOM to parse the result of the XML document.

However, manipulating XML documents is a computationally expensive operation for mobile devices, for the following reasons :

<i> XML Documents is lengthy.

They use tags to embed information, and the size of a XML document can get very big pretty quickly. A Large XML document means

That your device have to use the more bandwidth to download it, the which translates into higher cost.

<ii> XML Documents is more difficult to process.

As shown earlier, you had to use DOM to traverse the tree in order to locate the information of your want. In addition, DOM itself have

To build the entire document on memory as a tree structure before you can traverse it. This is both memory and CPU intensive.

JSON (JavaScript Object Notation) is a lightweight data-interchange format that's easy for humans to read and write

It's also easy for machines to parse and generate.

[{"Appeid": "1" ," Survid ":"1" ," location ":" "," Surveydate ":" --Geneva  -" ," Surveytime ":" A: +: -" ," Inputuserid ":"1" ," Inputtime ":" --Geneva- -  A: +:Wuyi" ," Modifytime ":"0000-xx-xx xx:xx:xx"}, {" Appeid ":"2" ," Survid ":" +" ," location ":" "," Surveydate ":" --Geneva- -" ," Surveytime ":" A: +: the" ," Inputuserid ":" +" ," Inputtime ":" --Geneva- -  A: +:Panax Notoginseng" ," Modifytime ":"0000-xx-xx xx:xx:xx"}, {" Appeid ":"3" ," Survid ":" +" ," location ":" "," Surveydate ":" --Geneva- the" ," Surveytime ":" -: -: -" ," Inputuserid ":" +" ," Inputtime ":" --Geneva- the  ,:xx: -" ," Modifytime ":"0000-xx-xx xx:xx:xx"}]

Information is represented as a collection of key/value pairs. Each key/value pair is grouped to an ordered list of objects.

Unlike XML, there is no lengthy tag names, only brackets and braces.

Package Mirror.android.jsonservice;import Java.io.bufferedreader;import java.io.inputstream;import Java.io.inputstreamreader;import Org.apache.http.httpentity;import Org.apache.http.httpresponse;import Org.apache.http.statusline;import Org.apache.http.client.httpclient;import Org.apache.http.client.methods.httpget;import Org.apache.http.impl.client.defaulthttpclient;import Org.json.jsonarray;import Org.json.jsonexception;import Org.json.jsonobject;import Android.app.Activity;import Android.os.asynctask;import android.os.bundle;import android.util.log;import android.widget.Toast; Public classJsonactivity extends Activity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                Setcontentview (R.layout.activity_json); NewReadjsonfeedtask (). Execute ("Https://twitter.com/statuses/user_timeline/weimenglee.json"); }         Publicstring Readjsonfeed (String URL) {StringBuilder StringBuilder=NewStringBuilder (); HttpClient Client=Newdefaulthttpclient (); HttpGet HttpGet=NewHttpGet (URL); Try{HttpResponse response=Client.execute (HttpGet); Statusline Statusline=Response.getstatusline (); intStatusCode =Statusline.getstatuscode (); if(StatusCode = = $) {httpentity entity=response.getentity (); InputStreaminch=entity.getcontent (); BufferedReader Reader=NewBufferedReader (NewInputStreamReader (inch));                                String Line;  while(line = Reader.readline ())! =NULL) {stringbuilder.append (line); }            }            Else{LOG.E ("JSON","Failed to download file"); }        } Catch(Exception e) {e.printstacktrace (); }        returnstringbuilder.tostring (); }        Private classReadjsonfeedtask extends Asynctask<string, Void, string>{@Overrideprotectedstring Doinbackground (String ... urls) {returnReadjsonfeed (urls[0]); } @Overrideprotected voidOnPostExecute (String result) {Try{Jsonarray Jsonarray=NewJsonarray (Result); LOG.I ("JSON","Number of surveys in feed:"+jsonarray.length ());  for(inti =0; I < jsonarray.length (); i++) {Jsonobject jsonobject=Jsonarray.getjsonobject (i); Toast.maketext (Getapplication (), Jsonobject.getstring ("text") +" - "+ jsonobject.getstring ("Created_at"), Toast.length_short). Show (); }            } Catch(jsonexception e) {e.printstacktrace (); }        }    }}

Chapter Networking/json Services

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.