A detailed example of json programming

  • 2020-11-18 06:26:53
  • OfStack

An example of json programming is presented in this paper. To share for your reference, the details are as follows:

Definition of JSON:

A lightweight data interchange format that is readable and easy to write quickly. Mainstream technology in the industry provides a complete solution (somewhat similar to regular expressions, supported by most languages today) for data exchange between different platforms. JSON USES a highly compatible text format, but also has behavior similar to the C language system. � Json org

JSON Vs XML

1. Data readability of JSON and XML is basically the same

2.JSON and XML also have rich analytical tools

3. Compared with JSON, JSON is small in size

4. More convenient interaction between JSON and JavaScript

5.JSON's description of data is worse than XML's

6.JSON is much faster than XML

android2.3 provides the json parsing class

The json parsing part of android is under package ES47en. json, which mainly has the following classes:
JSONObject: Can be thought of as an json object, which is the basic unit of JSON definition in the system and contains 1 pair (Key/Value) values. Its response to the external (External: the value output by applying the toString() method) call is a standard string (for example: {"JSON": "Hello, World"}, wrapped in curly braces, where Key and Value are separated by the colon ":"). The operation format for the internal (Internal) behavior is slight, for example: initializing an instance of JSONObject and adding a value by referring to the internal put() method: new JSONObject().put ("JSON", "Hello, World!" ), separated by a comma "," between Key and Value. The types of Value include: Boolean, JSONArray, JSONObject, Number, String, or the default value JSONObject.NULL object.

JSONStringer: json text build class, which, according to the official explanation, helps create JSON text quickly and easily. The biggest advantage is that it reduces the number of program exceptions due to formatting errors. Referring to this class automatically creates JSON text strictly according to the syntax rules syntax rules. Only 1 JSON text can be created per JSONStringer entity. The biggest advantage of this is that it reduces the number of program exceptions due to formatting errors. Referring to this class automatically creates JSON text strictly according to the JSON syntax rules (syntax rules). Only 1 JSON text can be created per JSONStringer entity.

JSONArray: It represents an ordered set of values. Converts it to String output (toString) is in the form of exhibit with square brackets, value with a comma ", "space (for example: [value1 value2, value3], you can use more intuitive understanding of the short code format). Both get() and opt() methods can return the specified value via the index index. The 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 build the json text


//  Let's say I want to create something like this 1 a json The text  
// { 
//   "phone" : ["12345678", "87654321"], //  An array of  
//   "name" : "yuanzhifei89", //  string  
//   "age" : 100, //  The numerical  
//   "address" : { "country" : "china", "province" : "jiangsu" }, //  object  
//   "married" : false //  Boolean value  
// } 
try { 
  //  First of all, the outermost shell {} , is to create 1 An object  
  JSONObject person = new JSONObject(); 
  //  The first 1 A key phone The value of 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 create it again 1 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 for 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 it will fetch to the specified type, or throw JSONException if it cannot convert or has no value

optType also converts the value of the key to the specified type and returns the user-supplied or default supplied value if it cannot be converted or has no value


try { 
  //  All the objects used are those created above  
  //  Will be the first 1 Converts a number to a number and a name to a number  
  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); //  The default value provided by the user  
  person.optLong("name"); 
  person.optLong("name", 1000); //  Instead of throwing an exception like we did above, we return it 1000 
} catch (JSONException ex) { 
  //  Exception handling code  
} 

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


try { 
  JSONStringer jsonText = new JSONStringer(); 
  //  The first is { , the object begins. object and endObject Must be used in pairs  
  jsonText.object(); 
  jsonText.key("phone"); 
  //  key phone The value of theta is an array. array and endArray Must be used in pairs  
  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); 
  // } End of object  
  jsonText.endObject(); 
} catch (JSONException ex) { 
  throw new RuntimeException(ex); 
}

json text parsing class JSONTokener

Parse json text into corresponding objects according to the RFC4627 specification.

For parsing json text into objects, you only need two api of the class:

The constructor


public Object nextValue(); 
// { 
//   "phone" : ["12345678", "87654321"], //  An array of  
//   "name" : "yuanzhifei89", //  string  
//   "age" : 100, //  The numerical  
//   "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); 
  //  Nothing has been read at this point json Text, just read it directly 1 a JSONObject Object.  
  //  If the read position is at "name" :  , then, nextValue is "yuanzhifei89" ( String )  
  JSONObject person = (JSONObject) jsonParser.nextValue(); 
  //  And then the next thing is JSON Object operation  
  person.getJSONArray("phone"); 
  person.getString("name"); 
  person.getInt("age"); 
  person.getJSONObject("address"); 
  person.getBoolean("married"); 
} catch (JSONException ex) { 
  //  Exception handling code  
} 

The other api is basically for looking at text within json text


try { 
  JSONTokener jsonParser = new JSONTokener(JSON); 
  //  Read on 8 a json Characters in text. At the very beginning, at the very beginning { place  
  jsonParser.next(8); //{  "phone . tab calculate 1 A character  
  //  Read on 1 a json Characters in text  
  jsonParser.next(); //" 
  //  Read down 1 a json Characters in text. The character is not blank, nor is it the character in the gaze 
  jsonParser.nextClean(); //: 
  //  Returns the current read position to 1 Time meet 'a' Between the strings (not included a ).  
  jsonParser.nextString('a'); // ["12345678", "87654321"],  "n (Two Spaces in front)  
  //  Returns the current read position to 1 The second encounter in the string ( Such as "0089") A string between any characters, and the character is trimmed . (Here is no 1 Once met 89 )  
  jsonParser.nextTo("0089"); //me" : "yuanzhifei 
  //  Read position undo 1 a  
  jsonParser.back(); 
  jsonParser.next(); //i 
  //  Advance the read position to the specified string (including strings)  
  jsonParser.skipPast("address"); 
  jsonParser.next(8); //" : { "c 
  //  Advance the read position to the execution character (excluding characters)  
  jsonParser.skipTo('m'); 
  jsonParser.next(8); //married" 
} catch (JSONException ex) { 
  //  Exception handling code  
} 

Here is a standard JSON request implementation:


HttpPost request = new HttpPost(url);  
//  First encapsulation 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 the request   
HttpResponse httpResponse = new DefaultHttpClient().execute(request);  
//  You get a string of responses, and that's also 1 a  JSON  Data saved in format   
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 by myself, mainly adding 1 comment and explanation. This example mainly USES android to parse 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 for parsing 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);
        // Get returned Json string 
        String strResult = connServerForResult(strUrl);
        // parsing 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);
        // Get 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();
      //  To obtain HttpResponse object 
      HttpResponse httpResponse = httpClient.execute(httpRequest);
      if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        //  Gets 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 = jsonObjs.getJSONObject(i);
        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();
    }
  }
}

I hope this article has been helpful in Android programming.


Related articles: