Simple Android-JSON Application
JSON definition:
JSON (JavaScript Object Notation) is a lightweight data exchange format. It is based on a subset of JavaScript (Standard ECMA-262 3rd Edition-December 1999. JSON uses a completely language-independent text format, but it also uses a habit similar to the C language family (including C, C ++, C #, Java, JavaScript, Perl, Python, and so on ). These features make JSON an ideal data exchange language. Easy for reading and writing, and easy for machine parsing and generation (network transmission speed ).
Use in Andorid:
1. JSON Encapsulation
Android encapsulates a JSONObject class to save JSON. This class places data in JSONObject through the put method. In addition to basic types such as int and boolean, JSONObject can also store the JSONObject type and JSONArray type. The Code is as follows:
btnTest.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubJSONObject jsonObject = new JSONObject();try {jsonObject.put("name", "JACK");JSONObject Tel = new JSONObject();Tel.put("homeTel", "123456");Tel.put("companyTel", "654321");jsonObject.put("Tel", Tel);JSONArray Address = new JSONArray();Address.put("NingBo");Address.put("Shanghai");jsonObject.put("Address", Address);} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}etTest.setText(jsonObject.toString());}});
After clicking the ReadJson button, the system displays the JSONObject in EditText. :
2. parse JSON
After obtaining the JSONObject, the system uses the getXXX function to obtain the corresponding parameters in JSON.
Code:
btnTest.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubString JSON = "{\"name\":\"JACK\","+ "\"Address\":[\"Ningbo\",\"Shanghai\"],"+ "\"Tel\":{\"companyTel\":\"654321\",\"homeTel\":\"123456\"}}";String strOutput = "NULL";try {JSONObject jsonObject = new JSONObject(JSON);String strName = jsonObject.getString("name") + "\n";JSONArray jsonArray = jsonObject.getJSONArray("Address");String strAddress = jsonArray.getString(0) + ","+ jsonArray.getString(1) + "\n";JSONObject Tel = jsonObject.getJSONObject("Tel");String strCompanyTel = Tel.getString("companyTel");String strHomeTel = Tel.getString("homeTel");String strTel = strCompanyTel + "," + strHomeTel;strOutput = strName + strAddress + strTel;} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {etTest.setText(strOutput);}}});
: