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, but also easy to machine parse and generate, and is ideal for server-to-client interaction. JSON takes a text format that is not related to programming language, but also uses the C-class idiom, which makes 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, the JSON data format is simple, you can transfer a simple string,number,boolean with JSON, or you can transfer
An array, or a complex object. String,number and Boolean representations of JSON are very simple. For example, using JSON to represent a simple string

"ABC", in the format: "ABC". In addition to the characters ", \,/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 [] contains all elements, each element is separated by commas, and the element can be arbitrary
Value, for example, the following array contains a string,number,boolean and a null:

["ABC", 12345,false,null]

Object objects are represented in JSON with a series of unordered Key-value key-value pairs, actually
Object is equivalent to map<string in Java, Object&gt, not Java Class. Note that Key can only be used with the String table
Shown For example, an Address object contains the following key-value:
City:beijing
Street:chaoyang Road
postcode:100025 (integer)
This is represented by JSON:

{"City": "Beijing", "Street": "Chaoyang Road", "Postcode": 100025}
Where Value can also be another object or array, complex objects can be nested representations, for example, a
The Person object contains the name and address objects, which can be represented as follows:

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


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

This is written on the code I've written, and I'm going to write down the main code.

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 have written this before, inherited 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.

Here is an introduction to Android

The Android SDK provides Apache's HttpClient class to handle network access, and it is believed that many of the reader's friends use it in other projects
Been to HttpClient. I wrote a method class that gets the Web page content of a URL, with the following code:

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 parameter 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 this is a fixed class, as long as the use of JSON, you can take to use, for the time being, 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 ();}}}


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.