Core technology: JSON parsing of 6.android network programming

Source: Internet
Author: User

  Preface: Good time did not write a blog, said recently very busy, feel like an excuse, every day or the same 24 hours, every day or the same 5:30 on time to work, every night there is a lot of free time ... The most immediate reason is that the recent fall. Brain also often have a lot of ideas emerge, are some more practical ideas, but often is the emergence of that, the mood excited a bit, in the heart silently told himself, there is time to do so ... A lot of ideas have been erased by some other temptation, either by playing ball, watching movies, or dealing with a mess. In short, the recent period of time, spend less time on technology, a good reflection.

Some time ago, to a customer in Xinjiang, put forward a demand, the need is not difficult to achieve, just the customer is very hurry, hope in two days to get out, think at that time is still young, not much thought, promised down. There is a link to the customer's background to docking, back-end interface return data type is JSON, very simple data structure, not embedded many layers. But because of their previous and backstage docking with the always is webservice, suddenly out of a JSON, a bit blindfolded. However, for JSON so commonly used data structure, do not grasp its analytic method, oneself also should be good to reflect on. Just met this problem, think about the problem is finished must write a blog to well record the JSON parsing method, so that the later project use, you can quickly get started. But the project has been a long time, the blog has been pushed until today to start writing, the reason is like the opening said ...

 JSON definition: a Lightweight data interchange format with good readability and fast writing features, the industry's mainstream technology provides it with a complete solution that enables data interaction between different platforms.

 JSON parsing: before explaining the JSON parsing method, first understand the two basic concepts:

    1.JSONObject: A basic JSON object, the basic unit of JSON definition, is actually a bunch of key-value pairs (key/value), as a standard string, such as: {"name": "Dean"}. The outer brace is wrapped, and the inner key and value are separated by: the type of value includes: Boolean,jsonarray,jsonobject,number,string,jsonobject.null object.

    2.JSONArray: It represents a set of ordered values, the external expression is: the outermost square brackets wrapped, the values are separated by commas, such as: [Value1,value2,value3]

JSON has a total of four data formats:A. Direct object B. Array C. The object contains an array of D. The array contains an array in fact the same parsing principle, encountered object can directly call the Object.getstring () method to get the value,   When you encounter an array, convert to object one by one, and then call the Object.getstring () method to get value. The following code shows how the JSON is parsed:

//JSON object parsing directlyBtnobjectpaser.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {Try {                    //JSON stringString json= "{\" username\ ": \" dean\ ", \" age\ ": 23,\" addr\ ": \" Guangdong Guangzhou Tianhe District \ "}"; //get JSON object objects based on JSON stringJsonobject Jsonobject =NewJsonobject (JSON); //get the corresponding value based on keyString str= "Name:" +jsonobject.getstring ("username") + "Age:" +jsonobject.getstring ("ages") + "Address:" +jsonobject.getstring ( "addr") + "\ n";                Tvshowresult.settext (str); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace ();        }            }        }); //JSON Array Direct parsingBtnarraypaser.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {Try {                    //JSON stringString json= "[{\" username\ ": \" dean\ ", \" age\ ": \" 23\ ", \" addr\ ": \" Guangdong Guangzhou Tianhe District \ "}," + "{\" username\ ": \ "Xiao Zhang \", \ "age\": \ "32\", \ "addr\": \ "Guangdong province Guangzhou Baiyun District \"}] "; String Str= ""; //get a JSON array based on a JSON stringJsonarray Jsonarray =NewJsonarray (JSON);  for(intI=0;i<jsonarray.length (); i++) {Jsonobject jsonobject= (jsonobject) jsonarray.opt (i);//converts a JSON array through the OPT () function to Jsonobject//get the corresponding value based on keystr + = "Name:" +jsonobject.getstring ("username") + "Age:" +jsonobject.getstring ("ages") + "Address:" +jsonobject.getstring ("addr ") +" \ n ";                } tvshowresult.settext (str); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace ();        }            }        }); //there are arrays in the JSON objectBtnarrayinobject.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {Try {                    //JSON stringString json= "{\" username\ ": \" Zhang Mu sheng \ ", age:11,\" jicheng\ ": [{\" zhengshu\ ": \" Pmp\ ", \" date\ ": \" 2011 \ "}," + "{\" zhengshu\ ": \" Information System Project manager \ ", \" date\ ": \" 2012 \ "}],\" addr\ ": \" Jiangxi \ "}"; String Str= ""; //get a JSON object based on a JSON stringJsonobject Jsonobject =NewJsonobject (JSON); STR+ = "Name:" +jsonobject.getstring ("username") + "Age:" +jsonobject.getstring ("ages")); Jsonarray Jsonarray=NewJsonarray (jsonobject.getstring ("Jicheng"));  for(intI=0;i<jsonarray.length (); i++) {Jsonobject jsonObject2= (jsonobject) jsonarray.opt (i);//converts a JSON array through the OPT () function to Jsonobject//get the corresponding value based on keystr + = "Certificate:" +jsonobject2.getstring ("Zhengshu") + "Date:" +jsonobject2.getstring ("date") + ";"; } STR+ = "Address:" +jsonobject.getstring ("addr"));                Tvshowresult.settext (str); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace ();        }            }        }); //there are arrays in the JSON arrayBtnarrayinarray.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {Try {                    //JSON stringString json= "[" + "{\" devid\ ": \" 1234567800\ ", \" Gps\ ": [{\" time\ ": \" 2014-11-12\ ", \" latitude\ ": \" 29 .4963\ ", \" longitude\ ": \" 116.189\ "},{\" time\ ": \" 2014-11-12\ ", \" latitude\ ": \" 29.4963\ ", \" longitude\ ": \" 116.189\ " }],\ "devname\": \ "gan 01\"}, "+" {\ "devid\": \ "1234567800\", \ "Gps\": [{\ "time\": \ "2014-11-12\", \ "Lati Tude\ ": \" 29.4963\ ", \" longitude\ ": \" 116.189\ "},{\" time\ ": \" 2014-11-12\ ", \" latitude\ ": \" 29.4963\ ", \" Longitude\ " : \ "116.189\"}],\ "devname\": \ "gan 92\"}, "+" {\ "devid\": \ "1234567800\", \ "Gps\": [{\ "time\": \ "2014-1 1-12\ ", \" latitude\ ": \" 29.4963\ ", \" longitude\ ": \" 116.189\ "},{\" time\ ": \" 2014-11-12\ ", \" latitude\ ": \" 29.4963\ ", \ "Longitude\": \ "116.189\"}],\ "devname\": \ "gan 43\"} "+"] "; String Str= ""; //get a JSON array based on a JSON stringJsonarray Jsonarray =NewJsonarray (JSON);  for(intI=0;i<jsonarray.length (); i++) {Jsonobject jsonobject= (jsonobject) jsonarray.opt (i);//converts a JSON array through the OPT () function to Jsonobject//get the corresponding value based on keystr + = "ID:" +jsonobject.getstring ("Devid") + ","; //get second-level arrayJsonarray JsonArray2 =NewJsonarray (jsonobject.getstring ("GPs"));//Jsonarray jsonArray2 = Jsonobject.getjsonarray ("GPs");//You can also get a second-level array like this                         for(intJ=0;j<jsonarray2.length (); j + +) {Jsonobject jsonObject2=(Jsonobject) jsonarray2.opt (j); STR+ = "GPs Time:" +jsonobject2.getstring ("Times") + "GPS Longitude:" +jsonobject2.getstring ("latitude") + "GPS Dimension:" + Jsonobject2.getstring ("longitude") + ";"; } STR+ = "Device Name:" +jsonobject.getstring ("devname") + ".";                } tvshowresult.settext (str); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }        });

  

Core technology: JSON parsing of 6.android network programming

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.