JSON definition:
JSON (JavaScript Object Notation) is a lightweight data interchange format. It is based on a subset of JavaScript (standard ECMA-262 3rd edition-december 1999). JSON takes a completely language-independent text format, but also uses a similar idiom to the C language family (c, C + +, C #, Java,javascript, Perl, Python, etc.). These features make JSON an ideal data exchange language. Easy to read and write, but also easy to machine parse and generate (network transfer speed).
Use in Andorid:
1. Encapsulating JSON
The Android package has a class jsonobject for storing JSON. This class puts the data into jsonobject by using the Put method. Jsonobject can store jsonobject types and Jsonarray types in addition to basic types such as Int,boolean. The following code is used:
Btntest.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated Method Stubjsonobject Jsonobject = new Jsonobject (); try {jsonobject.put ("name", "JACK"); Jsonobject Tel = new Jsonobject (); Tel.put ("Hometel", "123456"); Tel.put ("Companytel", "654321"); Jsonobject.put ("Tel", tel); Jsonarray Address = new Jsonarray (); Address.put ("Ningbo"); Address.put ("Shanghai"); Jsonobject.put ("Address", address);} catch (Jsonexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} Ettest.settext (Jsonobject.tostring ());});
The system displays the Jsonobject in EditText after clicking the Readjson button. :
2. Parsing JSON
After the system obtains the Jsonobject object, the GETXXX function is used to obtain the corresponding parameters in the JSON.
Code:
Btntest.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated Method Stubstring JSON = "{\" name\ ": \" Jack\ "," + "\" address\ ": [\" ningbo\ ", \" Shanghai\ "]," + "\" tel\ ": {\" companytel\ ": \ "654321\", \ "hometel\": \ "123456\"}} "; String stroutput = "NULL"; try {jsonobject jsonobject = new Jsonobject (JSON); String strName = jsonobject.getstring ("name") + "\ n"; Jsonarray Jsonarray = Jsonobject.getjsonarray ("Address"); String straddress = jsonarray.getstring (0) + "," + jsonarray.getstring (1) + "\ n"; Jsonobject Tel = jsonobject.getjsonobject ("tel"); String Strcompanytel = tel.getstring ("Companytel"); String Strhometel = tel.getstring ("Hometel"); String Strtel = Strcompanytel + "," + strhometel;stroutput = strName + straddress + Strtel;} catch (Jsonexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} finally {Ettest.settext (stroutput);}});
:
Android-json Simple Application