Android example Analysis for JSON data parsing method _android

Source: Internet
Author: User
Tags exception handling numeric value parse error

This example describes the Android approach to JSON data parsing. Share to everyone for your reference. Specifically as follows:

The definition of JSON:

A lightweight data interchange format with good readability and fast-coding features. The industry's mainstream technology provides it with a complete solution (a bit like regular expressions that are supported by most languages today), allowing data exchange between platforms. JSON uses a highly compatible text format, as well as behavior similar to the C language system. –json.org

JSON Vs XML

1.JSON and XML are basically the same readability of data
2.JSON and XML also have rich analytical tools
3.JSON the volume of data is small relative to XML
4.JSON interaction with JavaScript is more convenient
5.JSON is less descriptive of data than XML
6.JSON is much faster than XML

JSON parsing class provided by android2.3

The JSON parsing section of Android is all under the package Org.json, and there are several main classes:

Jsonobject: Can be thought of as a JSON object, which is a basic unit of JSON definition in the system that contains a pair of child (Key/value) values. Its response to an external (External: The value of the output of the application ToString () method) is reflected as a standard string (for example: {"JSON": "Hello, World"}, wrapped in curly braces, where key and value are separated by a colon ":"). It has a slight operational format for internal (Internal) behavior, such as initializing a Jsonobject instance, and referencing the internal put () method to add a value: New Jsonobject (). Put ("JSON", "Hello, world!"), The key and value are separated by commas ",". The types of value include: Boolean, Jsonarray, Jsonobject, number, string, or Default value Jsonobject.null object.

The Jsonstringer:json text building class, which, according to the official explanation, can help create JSON text quickly and easily. The biggest advantage of this is that you can reduce the error in the format resulting in a program exception, referencing this class can automatically create JSON text strictly according to the JSON syntax rules (syntax rules). Only one JSON text can be created for each Jsonstringer entity. The biggest advantage of this is that you can reduce the error in the format resulting in a program exception, referencing this class can automatically create JSON text strictly according to the JSON syntax rules (syntax rules). Only one JSON text can be created for each Jsonstringer entity.

Jsonarray: It represents a set of ordered values. The form of converting it to string output (toString) is wrapped in square brackets, with values separated by commas "," (for example, [Value1,value2,value3], where you can use the short code to get a more intuitive understanding of its format). The interior of this class also has query behavior, and both the Get () and opt () methods can return the specified value through the index index, and the put () method is used to add or replace the numeric value. The value type of the same class can include Boolean, Jsonarray, Jsonobject, number, string, or Default value Jsonobject.null object.

Jsontokener:json Resolution Class

The exception used in the Jsonexception:json

Jsonobject, Jsonarray to build JSON text

Code:

Suppose you now want to create such a JSON text 
//{ 
//   "phone": ["12345678", "87654321"],//array 
//   "name": "Yuanzhifei89",/ /String 
//   "age": 100,//value 
//   "address": {"Country": "Country", "province": "Jiangsu"},//Object 
//< c11/> "Married": false//Boolean 
//} 
try { 
  //First outermost is {}, is to create an object jsonobject person 
  = new Jsonobject (); 
   //first key phone's value 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",); 
  The value of the key address is an object, so you have to create an object 
  jsonobject address = new Jsonobject (); 
  Address.put ("Country", "the"); 
  Address.put ("Province", "Jiangsu"); 
  Person.put ("Address", address);  
  Person.put ("Married", false); 
catch (Jsonexception ex) { 
  //key is null or a number format not supported by JSON (NaN, infinities) 
  throw new RuntimeException (ex); 


Use of the GetType and Opttype APIs

GetType can convert the value of the key being fetched to the specified type, or throw the jsonexception if it cannot be converted or if there is no value

Opttype is also the value of the key that will be fetched to the specified type, and returns the value provided by the user or provided by default when there is no conversion or no value

Code:

try {// 
  all objects used are the object created above 
  //Converts the first phone number to a numeric value and converts the name to a numeric 
  phone.getlong (0); 
  Person.getlong ("name"); Throws an exception because the name cannot be converted to long    
  phone.optlong (0);//code built-in default value 
  Phone.optlong (0, 1000);//user supplied default value 
  Person.optlong (" Name "); 
  Person.optlong ("name", 1000); Instead of throwing an exception like the above, it returns 1000 
} catch (Jsonexception ex) { 
  //exception handling code 
}

In addition to the two classes above, you can also use Jsonstringer to build JSON text
Java code:

try { 
  Jsonstringer jsontext = new Jsonstringer (); 
  First is {, the object begins. Object and EndObject must be paired using 
  jsontext.object (); 
  Jsontext.key ("Phone"); 
  The value of the key phone is an array. Array and Endarray must be paired using 
  jsontext.array (); 
  Jsontext.value ("12345678"). Value ("87654321"); 
  Jsontext.endarray (); 
  Jsontext.key ("name"); 
  Jsontext.value ("yuanzhifei89"); 
  Jsontext.key ("Age"); 
  Jsontext.value (m); 
  Jsontext.key ("Address"); 
  The value of the key address is the object 
  jsontext.object (); 
  Jsontext.key ("Country"); 
  Jsontext.value ("the"); 
  Jsontext.key ("Province"); 
  Jsontext.value ("Jiangsu"); 
  Jsontext.endobject (); 
  Jsontext.key ("Married"); 
  Jsontext.value (false); 
  The object ends 
  jsontext.endobject (); 
} catch (Jsonexception ex) { 
  throw new RuntimeException (ex); 
}

JSON text parsing class Jsontokener

Parses the JSON text into the appropriate object according to the RFC4627 specification.

For parsing JSON text as an object, you need to use only two APIs for that class:

constructor function:
Public Object nextValue ();

Code:

//{//"phone": ["12345678", "87654321"],///array "name": "Yuanzhifei89",//Word string//"age": 100,//value//"address": {"Country": "Country", "province": "Jiangsu"},///Object/"married": Fal SE//boolean/} private static final String JSON = "{" + "\ phone\": [\ 12345678\], \ "87654321\"], "+" \ "Nam E\ ":" Yuanzhifei89\ "," + "\" age\ ":", "+" \ "address\": {\ "country\": \ "China\", "province\": \ "Jiangsu 
\ "}," + "\" married\ ": false," + "}; 
  try {jsontokener jsonparser = new Jsontokener (JSON); 
  No JSON text has been read at this time, and direct reading is a Jsonobject object. 
  If the read position at this time is "name": Then NextValue is the "yuanzhifei89" (String) jsonobject person = (jsonobject) jsonparser.nextvalue (); 
  What follows is the operation of the JSON object Person.getjsonarray ("Phone"); 
  Person.getstring ("name"); 
  Person.getint ("Age"); 
  Person.getjsonobject ("Address"); 
Person.getboolean ("Married"); } catch (Jsonexception ex) {//Exception handling code} 

Other APIs are basically the code used to view text in JSON text:

try { 
  Jsontokener jsonparser = new Jsontokener (JSON); 
  Continue reading the characters in the 8 JSON text. At this very beginning, namely in {Place 
  Jsonparser.next (8);//{  "phone. tab count a character 
  //Continue reading the characters in the 1 JSON text 
  jsonparser.next ();/// 
  Continue reading the characters in a JSON text. The character is not blank, nor is the character Jsonparser.nextclean () in the gaze ();//// 
  returns the current read position to the string (excluding a) from the first encounter ' a '. 
  jsonparser.nextstring (' a ');//["12345678", "87654321"],  "N (preceded by two spaces) 
  ///Returns the current read position to the first encountered string (such as" 0089 " A string between any character, and the character is trimmed. (Here is the first encounter of the 
  Jsonparser.nextto) ("0089");//me ":" Yuanzhifei 
  //Read position to revoke a 
  jsonparser.back (); 
  Jsonparser.next (); I 
  //read position forward to the specified string (including the string) 
  jsonparser.skippast ("address"); 
  Jsonparser.next (8); ": {" C 
  //Read position forward to execution character entered prompt (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); 
First encapsulates a JSON object 
jsonobject param = new Jsonobject (); 
Param.put ("name", "Rarnu"); 
Param.put ("Password", "123456"); 
Bind to request Entry 
stringentity se = new stringentity (param.tostring ()); 
Request.setentity (SE); 
Send Request 
HttpResponse HttpResponse = new Defaulthttpclient (). Execute (request); 
Gets the answer string, which is also a JSON format saved data 
string retsrc = Entityutils.tostring (Httpresponse.getentity ()); 
Generate a JSON object 
jsonobject result = new Jsonobject (RETSRC); 
String token = result.get ("token");

Here's a small example of how to modify others, mainly by adding comments and explanations, the main example of which is using Android for JSON parsing.

Single data:

Copy Code code as follows:
{' singer ': {' id ': ' name ': ' Tom ', ' Gender ': ' Man '}}

Multiple data:

{"Singers": [
{' id ': #, ' name ': ' Tom ', ' Gender ': ' Man '},
{' id ': ', ' name ': ' Jerry, ' gender ': ' Man '},
{' id ': 04, ' Name ': ' Jim, ' gender ': ' Man '},
{' id ': ' name ': ' Lily, ' gender ': ' Female '}]}

The following class is primarily a method for parsing a single data Parsejson () and multiple Data Parsejsonmulti ():

The public class Jsonactivity extends activity {/** called the ' when ' is the ' The activity ' is a-created. Private TextView TVJ 
  Son 
  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); 
        Gets the returned JSON string string strresult = Connserverforresult (strURL); 
      Parses the JSON string Parsejson (strresult); 
    } 
    }); 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 strresult = ""; 
      try {//httpclient object HttpClient httpclient = new Defaulthttpclient (); 
      Obtain HttpResponse object HttpResponse HttpResponse = Httpclient.execute (HttpRequest); if (Httpresponse.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {//Get the returned data Strresult = Entityuti 
      Ls.tostring (Httpresponse.getentity ()); 
      The catch (Clientprotocolexception e) {tvjson.settext ("protocol error"); 
    E.printstacktrace (); 
      catch (IOException e) {tvjson.settext ("IO error"); E.printstacktraCE (); 
  return strresult; }//Normal JSON data parsing private void Parsejson (String strresult) {try {jsonobject jsonobj = new Jsonobject (str 
      Result). Getjsonobject ("singer"); 
      int id = jsonobj.getint ("id"); 
      String name = jsonobj.getstring ("name"); 
      String gender = jsonobj.getstring ("gender"); 
    Tvjson.settext ("ID number" +id + ", Name:" + name + ", Sex:" + gender); 
      catch (Jsonexception e) {System.out.println ("Json parse Error"); 
    E.printstacktrace (); }///parse json private void Parsejsonmulti (String strresult) {try {Jsonarray jsonobjs = new Jsono for multiple data 
      Bject (strresult). Getjsonarray ("singers"); 
      String s = ""; for (int i = 0; i < jsonobjs.length (); i++) {Jsonobject jsonobj = ((jsonobject) jsonobjs.opt (i)). GETJ 
        Sonobject ("singer"); 
        int id = jsonobj.getint ("id"); 
        String name = jsonobj.getstring ("name"); 
      String gender = jsonobj.getstring ("gender");  S + + "ID number" +id + ", Name:" + name + ", Sex:" + gender+ "\ n"; 
    } tvjson.settext (s); 
      catch (Jsonexception e) {System.out.println ("Jsons parse Error!"); 
    E.printstacktrace ();

 } 
  } 
}

I hope this article will help you with your Android program.

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.