Get started with Android Json

Source: Internet
Author: User
Tags parse error

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 JSON Vs XML 1. the data in JSON and XML are basically the same. JSON and XML have the same rich parsing methods. 3. JSON is smaller than XML. JSON and JavaScript interaction is more convenient 5. JSON is less descriptive than XML. 6. the JSON parsing speed is much faster than that of the json parsing class android provided by XML android2.3. in json, there are several main classes: JSONObject: it can be considered as a json object, which is the basic unit of the JSON definition in the system and 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 text in strict accordance with the JSON syntax rules (syntax rules. 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: exception JSONObject used in json. JSONArray is used to construct json text code. // assume that you want to create such a json text. // {// "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 {}, which is to create an object JSONObject person = new JSONObject (); // The phone value of the first key 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 nul L or use a numeric format (NaN, infinities) that is not supported by json throw new RuntimeException (ex );} getType and optType APIs use getType to convert the value of the key to the specified type, if the conversion fails or no value exists, the JSONException optType is thrown, and the value of the key to be obtained is converted to the specified type, return the value code www.2cto provided by the user or provided by the default. comtry {// All used objects use the object created above // convert the first phone number to a numeric value and the name to a numeric phone number. 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. o PtLong ("name"); person. optLong ("name", 1000); // returns the 1000} catch (JSONException ex) {// Exception Handling Code} except for the above two classes, you can also use JSONStringer to construct the json text Java code try {JSONStringer jsonText = new JSONStringer (); // The first is {, and 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 parses json text into corresponding objects according to RFC4627 specifications. To parse json text into an Object, you only need to use two APIs of this class: the constructor public Object nextValue (); Code // {// "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 \", \ "province \": \ "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 down 8 characters in json text. 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: 01 HttpPost request = new HttpPost (url); 02 // encapsulate a JSON object first 03 JSONObject param = new JSONObject (); 04param. put ("name", "rarnu"); 05param. put ("password", "123456"); 06 // bind to the request Entry 07 StringEntity se = new StringEntity (param. toString (); 08request. setEntity (se); 09 // send the request 10 HttpResponse httpResponse = new defaulthttpclient(.exe cute (request); 11 // The response string, this is also a 12 String retSrc = EntityUtils data saved in JSON format. toString (httpResponse. getEntity (); 13 // generate JSON object 1 4 JSONObject result = new JSONObject (retSrc); 15 String token = result. get ("token"); The following is a small example of modifying others by yourself. It mainly adds comments and explanations. This example mainly uses android for json parsing. 1 single data {'singer': {'id': 01, 'name': 'Tom ', 'gender ': 'male'} 2 multiple data {"singers": [3 {'id': 02, 'name': 'Tom ', 'gender': 'male '}, 4 {'id': 03, 'name': 'Jerry, 'gender': 'male'}, 5 {'id': 04, 'name': 'Jim, 'Gender': 'male'}, 6 {'id': 05, 'name': 'lily, 'gender ': the following classes are mainly used to parse a single data parseJson () and multiple data methods parseJsonMulti (): 01 public class JsonActivity extends Activity {02/** Called when the activity is first created. */03 private TextView tvJson; 04 Private Button btnJson; 05 private Button btnJsonMulti; 06 @ Override 07 public void onCreate (Bundle savedInstanceState) {08 super. onCreate (savedInstanceState); 09 setContentView (R. layout. main); 10 tvJson = (TextView) this. findViewById (R. id. tvJson); 11 btnJson = (Button) this. findViewById (R. id. btnJson); 12 btnJsonMulti = (Button) this. findViewById (R. id. btnJsonMulti); 13 btnJson. setOnClickListener (New View. onClickListener () {14 @ Override 15 public void onClick (View v) {16 // url 17 // String strUrl = "http: // 10.158.166.110: 8080/AndroidServer/JsonServlet "; 18 String strUrl = ServerPageUtil. getStrUrl (UrlsOfServer. JSON_SINGER); 19 // get the returned Json String 20 String strResult = connServerForResult (strUrl); 21 // parse the Json String 22 parseJson (strResult); 23} 24}); 25 btnJsonMulti. setOnClickListener (new View. O NClickListener () {26 @ Override 27 public void onClick (View v) {28 String strUrl = ServerPageUtil. getStrUrl (UrlsOfServer. JSON_SINGERS); 29 String strResult = connServerForResult (strUrl); 30 // get multiple Singer 31 parseJsonMulti (strResult); 32} 33 }); 34} 35 private String connServerForResult (String strUrl) {36 // HttpGet object 37 HttpGet httpRequest = new HttpGet (strUrl); 38 String strResult = ""; 39 try {40 // HttpClient object 41 HttpClient httpClient = new DefaultHttpClient (); 42 // get HttpResponse object 43 HttpResponse httpResponse = httpClient.exe cute (httpRequest); 44 if (httpResponse. getStatusLine (). getStatusCode () = HttpStatus. SC _ OK) {45 // get the returned data 46 strResult = EntityUtils. toString (httpResponse. getEntity (); 47} 48} catch (ClientProtocolException e) {49 tvJson. setText ("protocol error"); 50 e. PrintStackTrace (); 51} catch (IOException e) {52 tvJson. setText ("IO error"); 53 e. printStackTrace (); 54} 55 return strResult; 56} 57 // common Json data parsing 58 private void parseJson (String strResult) {59 try {60 JSONObject jsonObj = new JSONObject (strResult ). getJSONObject ("singer"); 61 int id = jsonObj. getInt ("id"); 62 String name = jsonObj. getString ("name"); 63 String gender = jsonObj. getString ("ge Nder "); 64 tvJson. setText ("id" + id + ", name:" + name + ", gender:" + gender); 65} catch (JSONException e) {66 System. out. println ("Json parse error"); 67 e. printStackTrace (); 68} 69} 70 // Json71 private void parseJsonMulti (String strResult) for parsing multiple data {72 try {73 JSONArray jsonObjs = new JSONObject (strResult ). getJSONArray ("singers"); 74 String s = ""; 75 for (int I = 0; I <jsonObjs. length (); I ++) {76 JSONObject jsonObj = (JSONObject) jsonObjs. opt (I) 77. getJSONObject ("singer"); 78 int id = jsonObj. getInt ("id"); 79 String name = jsonObj. getString ("name"); 80 String gender = jsonObj. getString ("gender"); 81 www.2cto.com s + = "id" + id + ", name:" + name + ", gender:" + gender + "\ n "; 82} 83 tvJson. setText (s); 84} catch (JSONException e) {85 System. out. println ("Jsons parse error! "); 86 e. printStackTrace (); 87} 88}

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.