Android basics 11: JSON parsing and simple examples

Source: Internet
Author: User
Tags parse error

1. JSON definition:
A lightweight data exchange format with good readability and ease of writing. Mainstream technologies in the industry provide a complete solution (similar to regular expressions and supported by most languages) to exchange data between different platforms. JSON adopts a highly compatible text format and has behaviors similar to the C language system. -Json.org
2. JSON vs XML
1. The data readability of JSON and XML is basically the same.
2. JSON and XML have the same rich parsing Methods
3. JSON is smaller than XML.
4. easier interaction between JSON and JavaScript
5. JSON is less descriptive than XML.
6. JSON is much faster than XML.
3. JSON parsing class provided by android2.3
The JSON parsing section of Android is in the org. JSON package, which mainly includes the following classes:
Jsonobject: It can be viewed as a JSON object, which is the basic unit related to the json definition in the system. It contains a pair of key/value values. Its response to an external call (External: Applying the value output by the tostring () method) is a standard string (for example, {"JSON": "Hello, world "}, the outmost is enclosed by braces, and the key and value are separated by the colon ). The operation format for internal (internal) behaviors is slightly. For example, to initialize a jsonobject instance, reference the internal put () method to add a value: New
Jsonobject (). Put ("JSON", "Hello, world! "), Separated by commas (,) between keys and values. Value types include: Boolean, jsonarray, jsonobject, number, string, or the default value jsonobject. null object.
Jsonstringer: JSON Text Build class. According to official explanations, this class can help you quickly and conveniently create JSON text. Its biggest advantage is that it can reduce program exceptions caused by format errors. referencing this class can automatically create JSON text in strict accordance with the JSON syntax rules (syntax rules. Each jsonstringer object can only create one JSON text .. Its biggest advantage is that it can reduce program exceptions caused by format errors. referencing this class can automatically create JSON in strict accordance with the JSON syntax rules (syntax rules ).
Text. Each jsonstringer object can only create one JSON text.
Jsonarray: It represents a group of ordered values. The format of tostring output is enclosed in square brackets. Values are separated by commas (,) ([value1, value2, value3], you can use the short code to learn more about the format ). This class has the same internal query behavior. The get () and OPT () methods can both return the specified value through the index, and the put () method is used to add or replace the value. The Value Type of this class can also include: Boolean, jsonarray, jsonobject, number, string, or the default value jsonobject. null.
Object.
Jsontokener: JSON parsing class

Jsonexception: Exceptions used in JSON

Jsonobject and jsonarray to build JSON text

// Assume that the following JSON text is to be created: // {// "phone": ["12345678", "87654321"], // array // "name ": "yuanzhifei89", // string // "Age": 100, // value // "Address": {"country": "China", "Province ": "Jiangsu"}, // object // "married": false // Boolean value //} Try {// first the outermost layer is {}, is to create an object jsonobject person = new jsonobject (); // the value of the first key phone is an array, so you need to create an array object jsonarray phone = new jsonarray (); phone. put ("12345678 "). put ("87654321"); person. put ("phone", phone); person. put ("name", "yuanzhifei89"); person. put ("Age", 100); // The Key address value is an object, so you have to create an object jsonobject address = new jsonobject (); Address. put ("country", "China"); Address. put ("Province", "Jiangsu"); person. put ("Address", address); person. put ("married", false);} catch (jsonexception ex) {// The Key is null or the Nan, infinities format is not supported by JSON) throw new runtimeexception (Ex );}

Use of GetType and opttype APIs
GetType can convert the value of the key to be obtained to the specified type. If the key cannot be converted or there is no value, jsonexception is thrown.
Opttype is also the value of the key to be obtained to the specified type. If the key cannot be converted or no value is available, the value provided by the user or the default value is returned.

Try {// All used objects use the object created above // convert the first phone number to a value and the name to a value phone. getlong (0); person. getlong ("name"); // an exception is thrown because the name cannot be converted to long phone. optlong (0); // The default phone value built in the code. optlong (0, 1000); // The default value person provided by the user. optlong ("name"); person. optlong ("name", 1000); // returns the 1000} catch (jsonexception ex) {// Exception Handling Code} instead of throwing an exception as above}

In addition to the above two classes, you can also use jsonstringer to build JSON text

Try {jsonstringer jsontext = new jsonstringer (); // The object starts. Objects and endobject must be paired with jsontext. Object (); jsontext. Key ("phone"); // the value of the key phone is an array. The array and endarray must be paired with jsontext. array (); jsontext. value ("12345678 "). value ("87654321"); jsontext. endarray (); jsontext. key ("name"); jsontext. value ("yuanzhifei89"); jsontext. key ("Age"); jsontext. value (100); jsontext. key ("Address"); // The Key address value is jsontext. object (); jsontext. key ("country"); jsontext. value ("China"); jsontext. key ("Province"); jsontext. value ("Jiangsu"); jsontext. endobject (); jsontext. key ("married"); jsontext. value (false); //}. The object ends with jsontext. endobject ();} catch (jsonexception ex) {Throw new runtimeexception (Ex );}

JSON text parsing class jsontokener
Parse JSON text into corresponding objects according to rfc4627 specifications.

For parsing JSON text as an object, you only need to use two APIs of this class:
Constructor
Public object nextvalue ();

// {// "Phone": ["12345678", "87654321"], // array // "name": "yuanzhifei89 ", // string // "Age": 100, // value // "Address": {"country": "China", "Province": "Jiangsu "}, // object // "married": false // Boolean //} Private Static final string JSON = "{" + "\" phone \": [\ "12345678 \", \ "87654321 \"], "+" \ "Name \": \ "yuanzhifei89 \", "+" \ "Age \": 100, "+" \ "address \": {\ "country \": \ "China \", \ "prov Ince \ ": \" Jiangsu \ "}," + "\" Married \ ": false," + "}"; try {jsontokener jsonparser = new jsontokener (JSON ); // at this time, no JSON text has been read. Direct Reading is a jsonobject object. // If the read location is "name": Now, nextvalue is "yuanzhifei89" (string) jsonobject person = (jsonobject) jsonparser. nextvalue (); // The next step is to operate person on the JSON object. getjsonarray ("phone"); person. getstring ("name"); person. getint ("Age"); person. getjsonobject ("Address"); person. getboolean ("married");} catch (jsonexception ex) {// Exception Handling Code}

Other APIs are used to view the text in JSON text.

Try {jsontokener jsonparser = new jsontokener (JSON); // continue to read the characters in 8 JSON texts. At the beginning, jsonparser. Next (8); // {"phone. Tab is a character. // continue to read the characters jsonparser. Next (); // "// continue to read the characters in a JSON text. This character is not a blank character, nor is it the jsonparser character in the eyes. nextclean (); //: // returns the string (excluding a) between the current read location and the first encounter 'A ). Jsonparser. nextstring ('A'); // ["12345678", "87654321"], "N (there are two spaces in front) // return the string between the current reading position and any character in the first encountered string (such as "0089"). The character is also trimmed. (This is the first time I met 89) jsonparser. nextoff( "0089"); // me ":" yuanzhifei // detaches A jsonparser from the read location. back (); jsonparser. next (); // I // read position forward to the specified string (including string) jsonparser. skippast ("Address"); jsonparser. next (8); // ": {" C // read position forward to the execution character (excluding characters) jsonparser. skipto ('M'); jsonparser. next (8); // married "} catch (jsonexception ex) {// Exception Handling Code}

The following is a standard JSON request implementation process:

Httppost request = new httppost (URL); // encapsulate a JSON object jsonobject Param = new jsonobject (); Param. put ("name", "rarnu"); Param. put ("password", "123456"); // bind to the request entry stringentity Se = new stringentity (Param. tostring (); Request. setentity (SE); // send the request httpresponse = new defaulthttpclient(.exe cute (request); // The response string, which is also a string retsrc = entityutils stored in JSON format. tostring (httpresponse. getentity (); // generate JSON object jsonobject result = new jsonobject (retsrc); string token = result. get ("token ");

The following is a small example of modifying others by yourself. It mainly adds some comments and explanations. This example mainly uses Android for JSON parsing.

Single Data {'singer': {'id': 01, 'name': 'Tom ', 'gender': 'male'} multiple data {"Singers ": [{'id': 02, 'name': 'Tom ', 'gender': 'male'}, {'id': 03, 'name': 'Jerry, 'Gender': 'male'}, {'id': 04, 'name': 'Jim, 'gender': 'male'}, {'id': 05, 'name': 'lily, 'gender': 'female '}]}

The following classes are mainly used to parse a single data parsejson () and multiple data methods parsejsonmulti ():

Public class jsonactivity extends activity {/** called when the activity is first created. */private textview tvjson; private button btnjson; private button btnjsonmulti; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); tvjson = (textview) This. findviewbyid (R. id. tvjson); btnjson = (button) This. findviewbyid (R. id. btnjson ); Btnjsonmulti = (button) This. findviewbyid (R. id. btnjsonmulti); btnjson. setonclicklistener (new view. onclicklistener () {@ override public void onclick (view v) {// URL // string strurl = "http: // 10.158.166.110: 8080/androidserver/jsonservlet "; string strurl = serverpageutil. getstrurl (urlsofserver. json_singer); // obtain the returned JSON string strresult = connserverforresult (strurl); // parse the JSON string parsejson (strr Esult) ;}}); btnjsonmulti. setonclicklistener (new view. onclicklistener () {@ override public void onclick (view v) {string strurl = serverpageutil. getstrurl (urlsofserver. json_singers); string strresult = connserverforresult (strurl); // obtain multiple singer parsejsonmulti (strresult) ;}});} private string connserverforresult (string strurl) {// httpget object httpget httprequest = new httpget (strurl); string strre Sult = ""; try {// httpclient object httpclient = new response (); // get httpresponse object httpresponse = httpclient.exe cute (httprequest); If (httpresponse. getstatusline (). getstatuscode () = httpstatus. SC _ OK) {// obtain the returned data strresult = entityutils. tostring (httpresponse. getentity () ;}} catch (clientprotocolexception e) {tvjson. settext ("protocol error"); E. printstacktrace ();} Catch (ioexception e) {tvjson. settext ("Io error"); E. printstacktrace ();} return strresult;} // parse private void parsejson (string strresult) {try {jsonobject jsonobj = new jsonobject (strresult ). getjsonobject ("Singer"); int id = jsonobj. getint ("ID"); string name = jsonobj. getstring ("name"); string gender = jsonobj. getstring ("gender"); tvjson. settext ("ID" + ID + ", name:" + name + ", Gender :" + Gender);} catch (jsonexception e) {system. out. println ("JSON Parse error"); E. printstacktrace () ;}/// jsonprivate void parsejsonmulti (string strresult) for parsing multiple data {try {jsonarray jsonobjs = new jsonobject (strresult ). getjsonarray ("Singers"); string S = ""; for (INT I = 0; I <jsonobjs. length (); I ++) {jsonobject jsonobj = (jsonobject) jsonobjs. opt (I )). getjsonobject ("Singer"); int id = jsonobj. get INT ("ID"); string name = jsonobj. getstring ("name"); string gender = jsonobj. getstring ("gender"); S + = "ID" + ID + ", name:" + name + ", Gender:" + gender + "\ n";} tvjson. settext (s);} catch (jsonexception e) {system. out. println ("jsons Parse error! "); E. printstacktrace ();}}}

Reference: Android JSON parsing and simple example

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.