Android json parsing Content learning notes

Source: Internet
Author: User

Without a doubt, Json is the most popular data exchange format nowadays. Thanks to its ease of use, json has never been systematically learned about json, so I want to sort out json-related learning content. Json is a lightweight exchange format with good readability and ease of writing. It is supported by most languages and supports data exchange on different platforms, ideal because of its excellent features, it quickly replaced xml. All json-related data is used to list the comparison between json and xml, so I also copy the advantages: simpler than the xml format; json is a better data exchange format; xml is a better format for document exchange. json is easier to read on machines and can be supported by a browser client using a simple client library or its own support (javascript; supports a variety of common data structures, such as records, lists, and trees. 21 languages Support parsing and generating json formats. Disadvantages: No CDATA-like features in xml, it is not suitable for transmitting binary data such as audio and images. json does not have the display capability, which is not extensible than xml. -------------------------------------------- I read Ruan Yifeng's blog some time ago. I wrote an article about the data type and json. I thought it was very good and I spoke about some concepts easily, it is easy to understand. The content is as follows: in terms of structure, all data can be divided into three types: the first type is scalar ), that is, a separate string or number (numbers), such as the word "Beijing. The second type is sequence, that is, several related data are grouped together in a certain order, also called array or List, for example, "Beijing, shanghai ". The third type is mapping, that is, a Name/value pair (Name/value). That is, the data has a Name and a corresponding value, this is also called hash or dictionary, for example, "capital: Beijing ". The smallest unit of data structure is so simple! It is no wonder that in programming languages, as long as arrays and objects are available, all data can be stored. The Json specification is very simple. It can be clearly stated in just a few hundred words on a page, and this specification never needs to be upgraded, because it is stipulated in this provision. 1) Separate the parallel data with commas. 2) The ing is represented by a colon. 3) The set (array) of the parallel data is represented by square brackets. 4) The ing set (object) is represented by braces. The above four rules are all in Json format. Finally ---------------------------------- after reading some android json reference materials, I plan to write an example of parsing json by myself, so that I will be more impressed with the problems encountered in the code, the two demos are combined. The two parsing methods are the same, but they are different when constructing json. One is to place a jsp file on tomcat, some column strings described in json format are parsed and restored. The other is to build json format in the code before parsing. The following PO is the main code: the jsp file in tomcat is json. jsp, a string described in json format: [jav Ascript] <% @ page contentType = "text/html; charset = GBK" %> {"Race": "gnomizer", "Name": "Singleton doodle ", "Sion": "Mage", "Server": {"Server_region": "Zone 2", "Server_name": "Argus"}, "Talent ": ["Austria", "Flame"], "Achievement_Point": 12090, "P_Skill": ["engineering", "enchantment"], "L_Skill": ["first aid ", "Cooking", "archaeology", "phishing"], "plugin Sion": "Mage"} encapsulate a HttpUtil: [java] package com. eyu. json; import java. io. IOException; import java. util. arr AyList; import java. util. list; import java. util. map; import org. apache. http. httpResponse; import org. apache. http. nameValuePair; import org. apache. http. parseException; import org. apache. http. client. clientProtocolException; import org. apache. http. client. httpClient; import org. apache. http. client. methods. httpGet; import org. apache. http. client. methods. httpPost; import org. apache. http. impl. client. defaul THttpClient; import org. apache. http. message. basicNameValuePair; import org. apache. http. util. entityUtils; public class HttpUtil {public static HttpClient httpClient = new DefaultHttpClient (); public static String getRequest (String url) throws ParseException, IOException {// create an httpGet object HttpGet httpGet = new HttpGet (url); // send the Get request HttpResponse httpResponse = httpClient.exe cute (httpGet); // if the server returns successfully ECHO should be if (httpResponse. getStatusLine (). getStatusCode () = 200) {// obtain the server response String result = EntityUtils. toString (httpResponse. getEntity (); return result;} return null;} public static String postRequest (String url, Map <String, String> rawParams) throws ClientProtocolException, IOException {// create an httpPost object HttpPost httpPost = new HttpPost (url); // if many parameters are passed, you can encapsulate the passed parameters in List <NameValuePair> params = new RrayList <NameValuePair> (); for (String key: rawParams. keySet () {// encapsulate the request parameter params. add (new BasicNameValuePair (key, rawParams. get (key);} // send the post request HttpResponse httpResponse = httpClient.exe cute (httpPost); // if the server returns a response if (httpResponse. getStatusLine (). getStatusCode () = 200) {// obtain the server response String result = EntityUtils. toString (httpResponse. after getEntity (); return result;} return null ;}}, you can The parsing operation in y: [java] ...... string result = null; try {result = HttpUtil. getRequest ("http: // 10.0.2.2: 8080/jsontest/json. jsp "); Log. I ("PDA", "result -------->" + result);} catch (Exception e) {e. printStackTrace ();} JSONObject jsonObject = new JSONObject (result); txt_Name = (TextView) findViewById(R.id.txt _ Name); txt_Name.setText (jsonObject. getString ("Name"); txt_Race = (TextView) findViewBy Id(R.id.txt _ Race); txt_Race.setText (jsonObject. getString ("Race"); txt_upload sion = (TextView) findViewById(R.id.txt _ upload sion); txt_Profession.setText (jsonObject. getString ("sion Sion"); txt_ServerMsg = (TextView) findViewById(R.id.txt _ ServerMsg); txt_ServerMsg.setText (jsonObject. getJSONObject ("Server "). getString ("Server_region") + "," + jsonObject. getJSONObject ("Server "). getString ("Server_name ")); Txt_Talent = (TextView) findViewById(R.id.txt _ Talent); txt_Talent.setText (jsonObject. getJSONArray ("Talent "). getString (0) + "," + jsonObject. getJSONArray ("Talent "). getString (1 ));............................ pipeline ------------------------------------ another method is to directly build a json object: [java] // create a j Son object jsonObject = new JSONObject (); // put the string value in jsonObject. put ("Name", "Xindi Diandian"); jsonObject. put ("Race", "human"); jsonObject. put ("Death Sion", "Death Knight"); // The server information value is an object, so an object is created, then add the jsonObject serverMsg = new JSONObject (); serverMsg to the JSONObject object. put ("Server_region", "Zone 2"); serverMsg. put ("Server_name", "Argus"); jsonObject. put ("Server", serverMsg); // The value of the Talent information is an array, so create an array and add it to the jsonObject object. Y talent = new JSONArray (); talent. put ("blood "). put ("ice cream"); jsonObject. put ("Talent", talent); // place the integer in jsonObject. put ("Achievement_Point", 12090 );............................... the subsequent parsing methods are the same. The following are parsed:

 

Although Json Parsing is not often used now, this data exchange method must be mastered ~!

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.