Android JSON for network data exchange

Source: Internet
Author: User
Tags control characters

What is JSONJSON (JavaScript Object Notation) is a lightweight data interchange format that is easy to read and write, and easy to machine parse and build at the same time, and is well suited for server-to-client interaction.

JSON uses text formats that are not related to programming languages, but also use the C-class habit. These features make JSON an ideal data interchange format.

As with XML, JSON is also a data format based on plain text. Because JSON is inherently prepared for JavaScript, so. The JSON data format is easy, and you can use JSON to transmit a simple string,number. Boolean. can also transmit
An array. or a complex object. String,number and Boolean are very easy to use with JSON.

For example, using JSON to represent a simple string

"ABC". The format is: "ABC".

Except for the character ". \,/and some control characters (\b. \f,\n. \r,\t) need to be encoded, other Unicode characters can be output directly.


The Boolean type is expressed as true or false.

In addition, NULL in JAVASCRIPT is represented as NULL, and note that true, FALSE, and null do not have double-quotes, otherwise they will be treated as a String.


JSON can also represent an array object, using [] including all elements, each of which is separated by commas. Elements can be random.
Value. For example, the following array includes a string,number. Boolean and a null:

["ABC", 12345,false,null]

Object objects in JSON are represented by {} including a series of unordered Key-value key-value pairs. In fact, here
Object is equivalent to map<string in Java, object>. Rather than the Java Class. Note that Key can only be used with the String table
Shown For example, an Address object includes such as the following key-value:
City:beijing
Street:chaoyang Road
postcode:100025 (integer)
Demo sample with JSON table for example the following:

{"City": "Beijing", "Street": "Chaoyang Road", "Postcode": 100025}
The Value can also be an object or an array, so a complex object can be nested, for example. One
The person object includes the name and address objects and is able to perform samples such as the following:

{"Name": "Michael", "address": {"City": "Beijing", "Street": "Chaoyang Road", "Postcode": 100025}
}


Here is an example: (Remember server side to pilot package)

This is written in the code I wrote before. I'm writing down the main code now.

Create a new servlet:

Package Cn.four.json;import Java.io.ioexception;import Java.io.printwriter;import java.util.list;import Javax.print.event.printserviceattributeevent;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Net.sf.json.jsonarray;import Net.sf.json.jsonobject;import Cn.four.service.foundservice;import Cn.four.service.foundserviceimp;import Cn.four.user.found;public Class Jsondemoservlet extends HttpServlet {public void doget (HttpServletRequest request, httpservletresponse response) throws   Servletexception, IOException {foundservice fd=new foundserviceimp (); I've written about it.       Inherit interface list<found> List=fd.getfound ();      New one Listjsonobject jsb=new jsonobject ();           New A Jsonobject object Jsb.put ("Foundlist", list);     Get the data Jsonarray Fdarray=jsb.getjsonarray ("Foundlist") after the transfer; Save to Array response.setcontenttype ("Text/plain");//Solve garbled response.setcharacterencoding ("UTF-8"); PrIntwriter Out=response.getwriter ();   Out.write (Fdarray.tostring ()); Close Out.flush (); Out.close ();} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {}}
This is the end of the server side.

The following is an introduction to Android

The Android SDK provides Apache's HttpClient class handling network access, believing that many readers are using it in other projects
Been to HttpClient. I wrote a method class that gets the Web content of a URL, such as the following:

Package Com.four.http;import Java.io.bufferedreader;import Java.io.inputstreamreader;import Org.apache.http.httpentity;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.params.httpconnectionparams;import Org.apache.http.params.httpparams;public class Httpcontent { public string getcontent (string url) throws Exception {StringBuilder sb = new StringBuilder (); HttpClient client = new Defaulthttpclient (); Httpparams httpparams = Client.getparams ();//Set Network timeout reference httpconnectionparams.setconnectiontimeout (HttpParams, 3000); Httpconnectionparams.setsotimeout (Httpparams, 5000); HttpResponse response = Client.execute (new HttpGet (URL)); httpentity entity = response.getentity (), if (entity! = null) {BufferedReader reader = new BufferedReader (New Inputstreamre Ader (Entity.getcontent (), "UTF-8"), 8192); String line = null;while (line = Reader.readline ())! = null){Sb.append (line + "\ n");} Reader.close ();} return sb.tostring ();}}

I feel that this is a fixed class that can be used only with JSON. Did not try, do not know right ah.

Package Com.example.mychat;import Java.util.arraylist;import Java.util.hashmap;import java.util.List;import Java.util.map;import Org.json.jsonarray;import Org.json.jsonobject;import Android.app.activity;import Android.os.bundle;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.Button; Import Android.widget.listview;import Android.widget.simpleadapter;import Com.four.http.httpcontent;public class User_tips extends Activity {httpcontent content = new Httpcontent ();p rivate Button btnshua;private ListView Xianshi; @Over rideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( r.layout.activity_user_tips) Btnshua = (Button) Findviewbyid (R.id.btnshua); Xianshi = (ListView) Findviewbyid ( R.ID.LISTVIEW1); Btnshua.setonclicklistener (new Shualistener ());} Class Shualistener implements Onclicklistener {@Overridepublic void OnClick (View v) {//TODO auto-generated method Stublis Txianshi ();}} Private list<map<string, object>> getmessg (String url) {list<map<string, object>> List = new arraylist<map<string, Object>> (); String body;try {body = content.getcontent (URL); Jsonarray array = new Jsonarray (body), for (int i = 0; i < array.length (); i++) {Jsonobject obj = array.getjsonobject (i) ; map<string, object> map = new hashmap<string, object> (), Map.put ("Foundname", Obj.getstring ("Foundname")); Map.put ("Foundplace", Obj.getstring ("Foundplace")); List.add (map);}} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} return list;} private void Listxianshi () {try {String url = "Http://10.20.180.34:8080/lostfound/JSONDemoServlet"; Simpleadapter adapter = new Simpleadapter (THIS,GETMESSG (URL), R.layout.list_item, new string[] {"Foundname", "username" }, new int[] {r.id.foundname, r.id.username}); Xianshi.setadapter (adapter);} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}


Android JSON for network data exchange

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.