In device communication, data interaction is often used. We use the HTTP protocol to send JSON data, the Android client to package the data, sent to the background server, the background parsing out.
Android Client assembled JSON string
The following assembly results are:
{"Data": [{"id": "12345", "name": "Zhang San"},{"id": "54321", "name": "John Doe"}]}
Jsonobject jsonobject = new jsonobject (); Jsonarray jsonarray = new jsonarray (); try { jsonobject.put ("name", "Zhang San"); jsonobject.put ("id", "12345"); jsonarray.put ( Jsonobject); Jsonobject = new jsonobject (); jsonobject.put (" Name ", " John Doe ") jsonobject.put (" id ", " 54321 "); jsonarray.put (Jsonobject); String json = "{\" data\ ":" + Jsonarray.tostring () + "}";         LOG.V ("Zd", "JSON"); result = new httputils (). SendJsonData ( Consant.ip + consant.url3, json); Mhandler.sendemptymessage (0x0001); } catch (jsonexception e) { e.printstacktrace (); }
/**
* Send data to server, encoding type is Utf-8
* Svrurl for server address
* Paramstr is a JSON string
* Send Type is POST
*/
Public string sendjsondata (STRING SVRURL, STRING PARAMSTR) {  LOG.V ("Zd", "Send json"); try { // Turns to the specified format byte[] requestdata = paramstr.getbytes (" UTF-8 "); httpurlconnection conn = null; DataOutputStream outStream = null; String MULTIPART_FORM_DATA = "Multipart/form-data"; // constructs an HTTP header for a POST request url url = new url (SVRURL); // Server address conn = (httpurlconnection) Url.openconnection (); &nBsp; conn.setdoinput (TRUE); // allow input conn.setdooutput (TRUE); // allow output Conn.setusecaches (false); // do not use caches Conn.setrequestmethod ("POST"); conn.setrequestproperty (" Accept-charset ", " gbk,utf-8;q=0.7,*;q=0.3 "); Conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("Content-type", multipart_form_data); conn.setrequestproperty ("Content-length", long.tostring (requestdata.length)); conn.setrequestproperty ("Data",  PARAMSTR); // Request parameter Content, Gets the connection stream object that is output to the network    &NBSp; outstream = new dataoutputstream (Conn.getoutputstream ()); outstream.write (requestdata, 0, requestdata.length); outstream.flush (); Outstream.close (); bytearrayoutputstream outstream2 = new bytearrayoutputstream (); int cah = conn.getresponsecode (); if (cah != 200) {    LOG.V ("Data", "Server Response error code:" + cah); return "0"; }else if ( CAH == 200) {            LOG.V ("Data", "Server responded successfully:" + CAH); } Inputstream inputstream = conn.getinputstream (); int len = 0; byte[] data = new byte[1024]; while (Len = inputstream.read (data) != -1) { outstream2.write (data, 0, Len); } Outstream2.close (); inputstream.close (); string reSponsestr = new string (Outstream2.tobytearray ());  LOG.V ("Data", "data = " + responsestr); return responsestr; } catch (exception e) { return ""; }}
Let's take a look at the backstage process.
Behind the scenes is Java using Tomcat as a server
Creates a dynamic Web project that receives the Dopost () method of the Servlet
Protected void dopost (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { Request.setcharacterencoding ("Utf-8"); string method = request.getparameter ("Method"). ToString (); System.out.println ("method = " + method); System.out.println (New date (). toLocaleString ()); string jsondata = getdata (Request); try { jsonstringtolist (Jsondata); } catch (Exception e) { e.printstacktrace (); } doget (Request, response);}
Public string getdata (httpservletrequest req) { string result = null; try { //input stream for package request bufferedreader br = new bufferedreader ( new InputStreamReader ((ServletInputStream) req.getinputstream (), "Utf-8")); //Buffer characters stringbuffer sb=new stringbuffer (""); String line; while ((Line=br.readline ())!=null) {&Nbsp; sb.append (line) ; } br.close ();//close buffer stream result=sb.tostring ();//convert to character system.out.println ("result = " + result); } catch (exception e) { e.printstacktrace (); } return result;}
Gets the stream of characters sent by the GetData () method, which is a JSON string
Next, parse the JSON string
Let's start by analyzing the characteristics of this JSON string.
{"Data": [{"id": "12345", "name": "Zhang San"},{"id": "54321", "name": "John Doe"}]}
It can be found that it conforms to such a type {key:value} i.e. Jsonobject type
Turn it into jsonobject by this way.
Jsonobject jsonobject = Jsonobject.fromobject (JSONSTR);
There are two situations where you know the key value and you don't know the key value.
The first one knows that we can take value directly from the key value
String msg = jsonobject.getstring ("Data"). ToString ();
The result of the removal is:
[{"id": "12345", "name": "Zhang San"},{"id": "54321", "name": "John Doe"}]
The second is to use an iterator when the value is not known as the key value.
for (iterator<?> iter = Jsonobject.keys (); Iter.hasnext ();) {String key = (string) iter.next (); String value = Jsonobject.get (key). ToString (); SYSTEM.OUT.PRINTLN (key + "/" + value); Map.put (key, value); }
Here the key and value
Corresponding data,[{"id": "12345", "name": "Zhang San"},{"id": "54321", "name": "John Doe"}]
Next, we'll analyze the value values we've taken out.
It is not difficult to find that it is a jsonarray type
We use a For loop to traverse this Jsonarray
There are also two cases here, knowing the key value and not knowing the key value
Know the key value directly according to key to take, do not know the use of iterators, as for the iterator does not do a detailed introduction
for (Int i = 0; i < jsonarray.size (); i++) { jsonobject = jsonarray.getjsonobject (i); map<string, string> map = new hashmap<string, string > (; for ) (Iterator<?> iter = jsonobject.keys (); iter.hasnext ();) { String key = (String) iter.next (); string value = jsonobject.get (Key). ToString (); system.out.println (key + "/" + value); Map.put (key, value); } //here is know key value, directly fetch data //String Name = jsonobject.getstring ("name"). toString (); // String id = jsonobject.getstring ("id"). toString (); // //system.out.println (name + "/" + ID);}
id/12345name/Zhang San id/54321name/John Doe
PS: The JSON data type we've passed here is jsonobject, and sometimes it's passed over Jsonarray type.
Jsonarray Jsonarray = Jsonarray.fromobject (JSONSTR);
Simply convert to Jsonarray.
This article is from the "climb over the mountains to see the Sea" blog, please be sure to keep this source http://670176656.blog.51cto.com/4500575/1692195
Java backend parsing JSON string sent by Android