Android native JSON and parsing JSON, androidjson
JSON data is a lightweight data exchange format. It is usually used in Android for data transmission between client and server interactions. For example, there are many jar packages for parsing JSON data on the Internet, but in the final analysis, the Android native method for parsing JSON data is used. Therefore, it is very important to master the Android native method for parsing JSON data.
The following describes how to generate JSON data and parse JSON data. The package used is org. json.
(1) method for generating JSON data:
For example, to generate such json text
{
"Phone": ["12345678", "87654321"], // Array
"Name": "dream9", // string
"Age": 100, // Value
"Address": {"country": "china", "province": "guangdong"}, // object
}
Try {JSONObject obj = new JSONObject (); // first create an object JSONArray phone = new JSONArray (); // Add data to the array. The serial number increases from 0 to phone. put ("12345678"); phone. put ("87654321"); obj. put ("phone", phone); obj. put ("name", "dream9"); obj. put ("age", 100); JSONObject address = new JSONObject (); address. put ("country", "china"); address. put ("province", "jiangsu"); obj. put ("address", address); Log. e ("huang", obj. toString ());
Result:
(2) JSON data parsing method (the above example ):
Private void anaylse (String data) {try {JSONObject obj = new JSONObject (String) data); JSONArray phone = obj. getJSONArray ("phone"); for (int t = 0; t <phone. length (); ++ t) {Log. e ("huang", phone. getString (t); // parse the phone array} Log. e ("huang", obj. getString ("name"); Log. e ("huang", obj. getInt ("age") + ""); JSONObject o = obj. getJSONObject ("address"); Log. e ("huang", o. getString ("country"); Log. e ("huang", o. getString ("province");} catch (JSONException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}
Result:
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.