Android json Analysis and Simple Examples

  • 2021-07-22 11:32:20
  • OfStack

A lightweight data exchange format with good readability and easy to write quickly. Mainstream technology in the industry provides a complete solution (somewhat similar to regular expressions, which is supported by most languages today), so that data can be exchanged between different platforms. JSON adopts a highly compatible text format and also has behavior similar to C language system. Json. org

JSON Vs XML

1. The data readability of JSON and XML is basically the same

2. JSON and XML also have rich parsing means

3. Compared with XML, the data volume of JSON is small

4. The interaction between JSON and JavaScript is more convenient

5. JSON is less descriptive of data than XML

6. The speed of JSON is much faster than that of XML

json parsing class provided by android 2.3

The json parsing part of android is under the package org. json, which mainly has the following classes:
JSONObject: Think of it as an json object, which is the basic unit of JSON definition in the system and contains one pair of Key/Value values. Its response to an external call (External: a numeric value from the toString () method) is embodied as a standard string (for example: {"JSON": "Hello, World"}, outermost wrapped in curly braces, where Key and Value are separated by a colon ":"). Its operation format for internal (Internal) behavior is slightly, for example: initialize an instance of JSONObject, and refer to the internal put () method to add values: new JSONObject (). put ("JSON", "Hello, World! "), separated by commas", "between Key and Value. The types of Value include: Boolean, JSONArray, JSONObject, Number, String, or the default value JSONObject. NULL object.

JSONStringer: json text building class, according to the official explanation, this class can help to create JSON text quickly and easily. Its greatest advantage is that it can reduce program exceptions caused by formatting errors. Referencing this class can automatically create JSON text strictly according to JSON syntax rules (syntax rules). Only one JSON text can be created for each JSONStringer entity. . Its greatest advantage is that it can reduce program exceptions caused by formatting errors. Referencing this class can automatically create JSON text strictly according to JSON syntax rules (syntax rules). Only one JSON text can be created for each JSONStringer entity.

JSONArray: It represents an ordered set of values. Converting it to String output (toString) is in the form of square brackets and values separated by commas "," (for example, [value1, value2, value3], you can use short code to understand its format more intuitively). This class also has query behavior inside. get () and opt () can both return the specified value through the index index, and put () method is used to add or replace the value. Similarly, the value type of this class can include: Boolean, JSONArray, JSONObject, Number, String, or the default value JSONObject. NULL object.

JSONTokener: json parsing class
JSONException: Exceptions Used in json

JSONObject, JSONArray to construct json text
Code


//  Suppose you want to create this now 1 A json Text  
// { 
//   "phone" : ["12345678", "87654321"], //  Array  
//   "name" : "yuanzhifei89", //  String  
//   "age" : 100, //  Numerical value  
//   "address" : { "country" : "china", "province" : "jiangsu" }, //  Object  
//   "married" : false //  Boolean value  
// } 
 
try { 
  //  First of all, the outermost layer is {} Is to create 1 Objects  
  JSONObject person = new JSONObject(); 
  //  No. 1 1 Keys phone 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); 
  //  Key address The value of is an object, so you want to create a 1 Objects  
  JSONObject address = new JSONObject(); 
  address.put("country", "china"); 
  address.put("province", "jiangsu"); 
  person.put("address", address);  
  person.put("married", false); 
} catch (JSONException ex) { 
  //  Key is null Or use json Unsupported number format (NaN, infinities) 
  throw new RuntimeException(ex); 
} 

Use of getType and optType api
getType can convert the value of the key to be fetched to the specified type, and if it cannot be converted or there is no value, JSONException is thrown
optType also converts the value of the key to be fetched to the specified type, and returns the user-supplied or this default-supplied value when it cannot be converted or there is no value
Code


try { 
  //  All the objects used are those created above  
  //  Will be 1 Phone numbers to numeric values and names to numeric values  
  phone.getLong(0); 
  person.getLong("name"); //  An exception is thrown because the name cannot be converted to long    
  phone.optLong(0); //  Default values built into the code  
  phone.optLong(0, 1000); //  User-supplied default  
  person.optLong("name"); 
  person.optLong("name", 1000); //  Instead of throwing an exception as above, return 1000 
} catch (JSONException ex) { 
  //  Exception handling code  
} 

In addition to the above two classes, you can use JSONStringer to build json text
Java code


try { 
  JSONStringer jsonText = new JSONStringer(); 
  //  The first is { Object begins. object And endObject Must be paired  
  jsonText.object(); 
   
  jsonText.key("phone"); 
  //  Key phone Is an array. array And endArray Must be paired  
  jsonText.array(); 
  jsonText.value("12345678").value("87654321"); 
  jsonText.endArray(); 
   
  jsonText.key("name"); 
  jsonText.value("yuanzhifei89"); 
  jsonText.key("age"); 
  jsonText.value(100); 
   
  jsonText.key("address"); 
  //  Key address The value of is an object  
  jsonText.object(); 
  jsonText.key("country"); 
  jsonText.value("china"); 
  jsonText.key("province"); 
  jsonText.value("jiangsu"); 
  jsonText.endObject(); 
   
  jsonText.key("married"); 
  jsonText.value(false); 
   
  // } Object ends  
  jsonText.endObject(); 
} catch (JSONException ex) { 
  throw new RuntimeException(ex); 
} 

json Text Parsing Class JSONTokener
Parse json text into corresponding objects according to RFC4627 specification.

For parsing json text into objects, only two api's of the class are needed:
Constructor
public Object nextValue();
Code


// { 
//   "phone" : ["12345678", "87654321"], //  Array  
//   "name" : "yuanzhifei89", //  String  
//   "age" : 100, //  Numerical value  
//   "address" : { "country" : "china", "province" : "jiangsu" }, //  Object  
//   "married" : false //  Boolean value  
// } 
 
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, just read it directly 1 A JSONObject Object.  
  //  If the read position at this time is in "name" :  So, then nextValue Is "yuanzhifei89" ( String )  
  JSONObject person = (JSONObject) jsonParser.nextValue(); 
  //  The next thing is JSON Object manipulates the  
  person.getJSONArray("phone"); 
  person.getString("name"); 
  person.getInt("age"); 
  person.getJSONObject("address"); 
  person.getBoolean("married"); 
} catch (JSONException ex) { 
  //  Exception handling code  
} 

Other api are basically used to view the text in json text

Code


try { 
  JSONTokener jsonParser = new JSONTokener(JSON); 
  //  Continue to read down 8 A json Characters in the text. At this time, it just started, that is, in { Department  
  jsonParser.next(8); //{  "phone . tab Calculate 1 Characters  
   
  //  Continue to read down 1 A json Characters in text  
  jsonParser.next(); //" 
   
  //  Continue reading down 1 A json Characters in the text. This character is not white space, nor is it a character in the gaze  
  jsonParser.nextClean(); //: 
   
  //  Returns the current read position to the 1 Second encounter 'a' String between (excluding a ).  
  jsonParser.nextString('a'); // ["12345678", "87654321"],  "n (There are two spaces in front)  
   
  //  Returns the current read position to the 1 The second time a string is encountered ( Such as "0089") A string between any character, and the character is trimmed Of. (This is the first 1 The first time I met 89 )  
  jsonParser.nextTo("0089"); //me" : "yuanzhifei 
   
  //  Read position revocation 1 A  
  jsonParser.back(); 
  jsonParser.next(); //i 
   
  //  The read position advances to the specified string (including the string)  
  jsonParser.skipPast("address"); 
  jsonParser.next(8); //" : { "c 
   
  //  The read position advances 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:


HttpPost request = new HttpPost(url); 
//  Package first 1 A  JSON  Object  
JSONObject param = new JSONObject(); 
param.put("name", "rarnu"); 
param.put("password", "123456"); 
//  Bind to a request  Entry 
StringEntity se = new StringEntity(param.toString());  
request.setEntity(se); 
//  Send a request  
HttpResponse httpResponse = new DefaultHttpClient().execute(request); 
//  The string that gets the reply, which is also the 1 A  JSON  Format saved data  
String retSrc = EntityUtils.toString(httpResponse.getEntity()); 
//  Generate  JSON  Object  
JSONObject result = new JSONObject( retSrc); 
String token = result.get("token"); 

The following is a small example of modifying others, mainly adding 1 comment and explanation. This example mainly uses android to analyze json.


 Single data {'singer':{'id':01,'name':'tom','gender':' Male '}} 
 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 classes are primarily methods that parse single data 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) { 
 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); 
  // Analyse 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 = EntityUtils.toString(httpResponse.getEntity()); 
  } 
 } catch (ClientProtocolException e) { 
  tvJson.setText("protocol error"); 
  e.printStackTrace(); 
 } catch (IOException e) { 
  tvJson.setText("IO error"); 
  e.printStackTrace(); 
 } 
 return strResult; 
 } 
 //  Ordinary Json Data parsing  
 private void parseJson(String strResult) { 
 try { 
  JSONObject jsonObj = new JSONObject(strResult).getJSONObject("singer"); 
  int id = jsonObj.getInt("id"); 
  String name = jsonObj.getString("name"); 
  String gender = jsonObj.getString("gender"); 
  tvJson.setText("ID No. "+id + ",  Name: " + name + ", Gender: " + gender); 
 } catch (JSONException e) { 
  System.out.println("Json parse error"); 
  e.printStackTrace(); 
 } 
 } 
  // Parsing multiple data Json
 private void parseJsonMulti(String strResult) { 
 try { 
  JSONArray jsonObjs = new JSONObject(strResult).getJSONArray("singers"); 
  String s = ""; 
  for(int i = 0; i < jsonObjs.length() ; i++){ 
  JSONObject jsonObj = ((JSONObject)jsonObjs.opt(i)) 
  .getJSONObject("singer"); 
  int id = jsonObj.getInt("id"); 
  String name = jsonObj.getString("name"); 
  String gender = jsonObj.getString("gender"); 
  s += "ID No. "+id + ",  Name: " + name + ", Gender: " + gender+ "\n" ; 
  } 
  tvJson.setText(s); 
 } catch (JSONException e) { 
  System.out.println("Jsons parse error !"); 
  e.printStackTrace(); 
 } 
 } 
} 

The above is the whole content of this paper, hoping to help everyone's study.


Related articles: