This article analyzes the json analysis method of Android programming. Share it for your reference, as follows:
Definition of JSON:
A lightweight data exchange format with good readability and easy to write quickly. The mainstream technology in the industry provides it with a complete solution (somewhat similar to regular expressions, supported by most languages today), allowing data exchange between different platforms. JSON adopts a highly compatible text format and also has behaviors similar to the C language system. –
JSON Vs XML
The data readability is basically the same as XML
It also has rich parsing methods like XML
Compared to XML, the size of the data is small
Interaction with JavaScript is more convenient
The descriptiveness of the data is worse than that of XML
The speed is much faster than XML
json parsing class provided by Android 2.3
The json parsing part of Android is all packaged, mainly with the following classes:
JSONObject: It can be regarded as a json object, which is the basic unit of JSON definition in the system, which contains a pair of (Key/Value) values. Its response to an external (External: numeric value output by applying the toString() method) is reflected in a standard string (for example: {"JSON": "Hello, World"}, with the outermost wrapped in braces, and the Key and Value are separated by colons":"). Its operation format for internal (Internal) behavior is slightly different. For example, initialize a JSONObject instance and add a value with the internal put() method: new JSONObject().put("JSON", "Hello, World!"), separated by commas" and "" between Key and Value. Types of Value include: Boolean, JSONArray, JSONObject, Number, String, or default object.
JSONStringer: json text construction class. According to the official explanation, this class can help create JSON text quickly and conveniently. Its biggest advantage is that it can reduce program exceptions due to format errors. Referring to this class can automatically create JSON text strictly in accordance with the JSON syntax rules (syntax rules). Each JSONStringer entity can only create one JSON text corresponding to it. . Its biggest advantage is that it can reduce program exceptions due to format errors. Referring to this class can automatically create JSON text strictly in accordance with the JSON syntax rules (syntax rules). Each JSONStringer entity can only create one JSON text corresponding to it.
JSONArray: It represents an ordered set of numeric values. The form of converting it to String output (toString) is wrapped in square brackets, and the values are separated by commas "," (for example: [value1, value2, value3], you can use short code to understand its format more intuitively). The inside of this class also has query behavior. Both get() and opt() methods can return the specified value through the index index, and the put() method is used to add or replace the value. The value types of this class can also include: Boolean, JSONArray, JSONObject, Number, String or default value object.
JSONTOkener: json parsing class
JSONException: Exception used in json
JSONObject, JSONArray to build json text
// Suppose you want to create such a json text now// { // "phone" : ["12345678", "87654321"], // Array// "name" : "yuanzhifei89", // String// "age" : 100, // Value// "address" : { "country" : "china", "province" : "jiangsu" }, // Object// "married" : false // Boolean// } try { // First of all, the outermost layer is {}, which 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(); ("12345678").put("87654321"); ("phone", phone); ("name", "yuanzhifei89"); ("age", 100); // The value of the key address is an object, so you need to create another object JSONObject address = new JSONObject(); ("country", "china"); ("province", "jiangsu"); ("address", address); ("married", false); } catch (JSONException ex) { // The key is null or use a numeric format that is not supported by json (NaN, infinities) throw new RuntimeException(ex); }
Use of getType and optType api
getType can convert the value of the key to be retrieved to the specified type, and throw a JSONException if it cannot be converted or there is no value.
optType also converts the value of the key to be retrieved to the specified type, and returns the value provided by the user or default provided by this when it cannot be converted or there is no value.
try { // All objects used are created above // Convert the first phone number to a numeric value and convert the name to a numeric value (0); ("name"); // Exception will be thrown because the name cannot be converted to long (0); // The built-in default value of the code (0, 1000); // Default value provided by the user ("name"); ("name", 1000); // Not throwing exceptions like above, but returning 1000} catch (JSONException ex) { //Exception handling code}
In addition to the above two classes, you can also use JSONStringer to build json text
try { JSONStringer jsonText = new JSONStringer(); // First is {, the object starts. object and endObject must be used in pairs (); ("phone"); // The value of the key phone is an array. array and endArray must be used in pairs (); ("12345678").value("87654321"); (); ("name"); ("yuanzhifei89"); ("age"); (100); ("address"); // The value of the key address is an object (); ("country"); ("china"); ("province"); ("jiangsu"); (); ("married"); (false); // }, object ends (); } catch (JSONException ex) { throw new RuntimeException(ex); }
json text parsing class JSONTOkener
According to RFC4627 specification, parse json text into corresponding objects.
To parse json text into 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\", \"province\" : \"jiangsu\" }," + " \"married\" : false," + "}"; try { JSONTokener jsonParser = new JSONTokener(JSON); // No json text has been read yet, and reading directly is a JSONObject object. // If the reading position at this time is "name" :, then nextValue is "yuanzhifei89" (String) JSONObject person = (JSONObject) (); // The next thing is the operation of the JSON object ("phone"); ("name"); ("age"); ("address"); ("married"); } catch (JSONException ex) { //Exception handling code}
Other APIs are basically used to view the text in json text
try { JSONTokener jsonParser = new JSONTokener(JSON); // Continue to read down the 8 characters in the json text. At this point, it is at { (8); //{ "phone.tab counts a character // Continue to read down 1 character in json text (); //" // Continue to read down a character in a json text. This character is not a blank character, nor is it a character in the eye (); //: // Returns the string between the current read position and the first encounter 'a' (excluding a). ('a'); // ["12345678", "87654321"], "n (there are two spaces in front) // Returns the string between any character in the first encounter string (such as "0089"), and the character is trimmed. (This is the first time I met 89) ("0089"); //me" : "yuanzhifei // Read position to undo one (); (); //i // Read position forward to the specified string (including string) ("address"); (8); //" : { "c // Read position advances to the execution character (excluding characters) ('m'); (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 firstJSONObject param = new JSONObject(); ("name", "rarnu"); ("password", "123456"); // Bind to request EntryStringEntity se = new StringEntity(()); (se); // Send a requestHttpResponse httpResponse = new DefaultHttpClient().execute(request); // Get the answer string, which is also a data saved in JSON formatString retSrc = (()); // Generate JSON objectsJSONObject result = new JSONObject( retSrc); String token = ("token");
The following is a small example of modifying others by yourself, mainly adding some comments and explanations. This example mainly uses Android for JSON analysis.
Single data
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 class is mainly a method parseJson() and multiple data 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) { (savedInstanceState); setContentView(); tvJson = (TextView) (); btnJson = (Button) (); btnJsonMulti = (Button) (); (new () { @Override public void onClick(View v) { // url // String strUrl = "http://10.158.166.110:8080/AndroidServer/JsonServlet"; String strUrl = (UrlsOfServer.JSON_SINGER); //Get the returned Json string String strResult = connServerForResult(strUrl); //Parse Json string parseJson(strResult); } }); (new () { @Override public void onClick(View v) { String strUrl = (UrlsOfServer.JSON_SINGERS); String strResult = connServerForResult(strUrl); //Get multiple Singers parseJsonMulti(strResult); } }); } private String connServerForResult(String strUrl) { // HttpGet object HttpGet httpRequest = new HttpGet(strUrl); String strResult = ""; try { // HttpClient object HttpClient httpClient = new DefaultHttpClient(); // Get the HttpResponse object HttpResponse httpResponse = (httpRequest); if (().getStatusCode() == HttpStatus.SC_OK) { // Get the returned data strResult = (()); } } catch (ClientProtocolException e) { ("protocol error"); (); } catch (IOException e) { ("IO error"); (); } return strResult; } // Ordinary Json data analysis private void parseJson(String strResult) { try { JSONObject jsonObj = new JSONObject(strResult).getJSONObject("singer"); int id = ("id"); String name = ("name"); String gender = ("gender"); ("ID number"+id + ", Name:" + name + ",gender:" + gender); } catch (JSONException e) { ("Json parse error"); (); } } //Json parsing multiple data private void parseJsonMulti(String strResult) { try { JSONArray jsonObjs = new JSONObject(strResult).getJSONArray("singers"); String s = ""; for(int i = 0; i < () ; i++){ JSONObject jsonObj = (i); int id = ("id"); String name = ("name"); String gender = ("gender"); s += "ID number"+id + ", Name:" + name + ",gender:" + gender+ "\n" ; } (s); } catch (JSONException e) { ("Jsons parse error !"); (); } } }
I hope this article will be helpful to everyone's Android programming design.