Understanding and parsing of JSON in android

Source: Internet
Author: User
Tags parse error

JSONObject and JSONArray to build json text
Code

// Assume that you want to create such a json text
//{
// "Phone": ["12345678", "87654321"], // Array
// "Name": "yuanzhifei89", // string
// "Age": 100, // Value
// "Address": {"country": "china", "province": "jiangsu"}, // object
// "Married": false // Boolean Value
//}

Try {
// First, the outermost layer is {}, which is to create an object.
JSONObject person = new JSONObject ();
// The phone value of the first key 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 );
// The value of the Key address is an object, so you have to create 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 is null or the numeric format (NaN, infinities) not supported by json is used)
Throw new RuntimeException (ex );
}

Use of getType and optType APIs

GetType can convert the value of the key to be obtained to the specified type. If the key cannot be converted or there is no value, JSONException is thrown.
OptType is also the value of the key to be obtained to the specified type. If the key cannot be converted or no value is available, the value provided by the user or the default value is returned.

Code

Try {
// All objects used use the object created above
// Convert the first phone number to a value and the name to a value
Phone. getLong (0 );
Person. getLong ("name"); // an exception is thrown because the name cannot be converted to long
Phone. optLong (0); // default value embedded in the code
Phone. optLong (0, 1000); // default value provided by the user
Person. optLong ("name ");
Person. optLong ("name", 1000); // unlike the previous exception, 1000 is returned.
} Catch (JSONException ex ){
// Exception Handling Code
}

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

Try {
JSONStringer jsonText = new JSONStringer ();
// The first is {, the object starts. Objects and endObject must be paired
JsonText. object ();

JsonText. key ("phone ");
// The phone key value is an array. Array and endArray must be paired
JsonText. array ();
Maid. value ("12345678"). value ("87654321 ");
JsonText. endArray ();

JsonText. key ("name ");
JsonText. value ("yuanzhifei89 ");
JsonText. key ("age ");
JsonText. value (100 );

JsonText. key ("address ");
// The Key address value 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 ended
JsonText. endObject ();
} Catch (JSONException ex ){
Throw new RuntimeException (ex );
}

Json text parsing class JSONTokener
Parse json text into corresponding objects according to RFC4627 specifications.

For parsing json text as an object, you only need to use two APIs of this class:
Constructor
Public Object nextValue ();
Code

//{
// "Phone": ["12345678", "87654321"], // Array
// "Name": "yuanzhifei89", // string
// "Age": 100, // 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 has been read. Direct Reading is a JSONObject object.
// If the read location is "name": Now, nextValue is "yuanzhifei89" (String)
JSONObject person = (JSONObject) jsonParser. nextValue ();
// The next step is the JSON object operation.
Person. getJSONArray ("phone ");
Person. getString ("name ");
Person. getInt ("age ");
Person. getJSONObject ("address ");
Person. getBoolean ("married ");
} Catch (JSONException ex ){
// Exception Handling Code
}

Other APIs are used to view the text in json text.
Code

Try {
JSONTokener jsonParser = new JSONTokener (JSON );
// Continue to read down 8 characters in json text. At this point, it is {
JsonParser. next (8); // {"phone. A tab is a character.

// Continue to read 1 character in json text
JsonParser. next ();//"

// Continue to read down a character in the json text. This character is not a blank character, nor is it a character in watching
JsonParser. nextClean ();//:

// Return the string (excluding a) between the current reading position and the first encounter 'A ).
JsonParser. nextString ('A'); // ["12345678", "87654321"], "n (there are two spaces in front)

// Return the string between the current reading position and any character in the first encountered string (such as "0089"). The character is also trimmed. (This is the first time I met 89)
JsonParser. nexser ("0089"); // me ":" yuanzhifei

// Undo a read location
JsonParser. back ();
JsonParser. next (); // I

// Read position forward to specified string (including string)
JsonParser. skipPast ("address ");
JsonParser. next (8); // ": {" c

// Read position forward 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:
01 HttpPost request = new HttpPost (url );
02 // encapsulate a JSON object first
03 JSONObject param = new JSONObject ();
04 param. put ("name", "rarnu ");
05 param. put ("password", "123456 ");
06 // bind to the request Entry
07 StringEntity se = new StringEntity (param. toString ());
08 request. setEntity (se );
09 // send the request
10 HttpResponse httpResponse = new defaulthttpclient(cmd.exe cute (request );
11 // obtain the response string, which is also a data saved in JSON format
12 String retSrc = EntityUtils. toString (httpResponse. getEntity ());
13 // generate a JSON object
14 JSONObject result = new JSONObject (retSrc );
15 String token = result. get ("token ");

The following is a small example of modifying others by yourself. It mainly adds some comments and explanations. This example mainly uses android for json parsing.
1 single data {'singer': {'id': 01, 'name': 'Tom ', 'Gender': 'mal '}}
2 multiple data {"singers ":[
3 {'id': 02, 'name': 'Tom ', 'gender': 'male '},
4 {'id': 03, 'name': 'Jerry, 'gender': 'male '},
5 {'id': 04, 'name': 'Jim, 'gender': 'male '},
6 {'id': 05, 'name': 'lily, 'gender': 'female}]}
The following classes are mainly used to parse a single data parseJson () and multiple data methods parseJsonMulti ():
01 public class JsonActivity extends Activity {
02/** Called when the activity is first created .*/
03 private TextView tvJson;
04 private Button btnJson;
05 private Button btnJsonMulti;
06 @ Override
07 public void onCreate (Bundle savedInstanceState ){
08 super. onCreate (savedInstanceState );
09 setContentView (R. layout. main );
10 tvJson = (TextView) this. findViewById (R. id. tvJson );
11 btnJson = (Button) this. findViewById (R. id. btnJson );
12 btnJsonMulti = (Button) this. findViewById (R. id. btnJsonMulti );
13 btnJson. setOnClickListener (new View. OnClickListener (){
14 @ Override
15 public void onClick (View v ){
16 // url
17 // String strUrl = "http: // 10.158.166.110: 8080/AndroidServer/JsonServlet ";
18 String strUrl = ServerPageUtil. getStrUrl (UrlsOfServer. JSON_SINGER );
19 // obtain the returned Json string
20 String strResult = connServerForResult (strUrl );
21 // parse the Json string
22 parseJson (strResult );
23}
24 });
25 btnJsonMulti. setOnClickListener (new View. OnClickListener (){
26 @ Override
27 public void onClick (View v ){
28 String strUrl = ServerPageUtil. getStrUrl (UrlsOfServer. JSON_SINGERS );
29 String strResult = connServerForResult (strUrl );
30 // obtain multiple singers
31 parseJsonMulti (strResult );
32}
33 });
34}
35 private String connServerForResult (String strUrl ){
36 // HttpGet object
37 HttpGet httpRequest = new HttpGet (strUrl );
38 String strResult = "";
39 try {
40 // HttpClient object
41 HttpClient httpClient = new DefaultHttpClient ();
42 // get the HttpResponse object
43 HttpResponse httpResponse = httpClient.exe cute (httpRequest );
44 if (httpResponse. getStatusLine (). getStatusCode () = HttpStatus. SC _ OK ){
45 // get the returned data
46 strResult = EntityUtils. toString (httpResponse. getEntity ());
47}
48} catch (ClientProtocolException e ){
49 tvJson. setText ("protocol error ");
50 e. printStackTrace ();
51} catch (IOException e ){
52 tvJson. setText ("IO error ");
53 e. printStackTrace ();
54}
55 return strResult;
56}
57 // common Json data parsing
58 private void parseJson (String strResult ){
59 try {
60 JSONObject jsonObj = new JSONObject (strResult). getJSONObject ("singer ");
61 int id = jsonObj. getInt ("id ");
62 String name = jsonObj. getString ("name ");
63 String gender = jsonObj. getString ("gender ");
64 tvJson. setText ("id" + id + ", name:" + name + ", gender:" + gender );
65} catch (JSONException e ){
66 System. out. println ("Json parse error ");
67 e. printStackTrace ();
68}
69}
70 // parse the Json of multiple data
71 private void parseJsonMulti (String strResult ){
72 try {
73 JSONArray jsonObjs = new JSONObject (strResult). getJSONArray ("singers ");
74 String s = "";
75 for (int I = 0; I <jsonObjs. length (); I ++ ){
76 JSONObject jsonObj = (JSONObject) jsonObjs. opt (I ))
77. getJSONObject ("singer ");
78 int id = jsonObj. getInt ("id ");
79 String name = jsonObj. getString ("name ");
80 String gender = jsonObj. getString ("gender ");
81 s + = "id" + id + ", name:" + name + ", gender:" + gender + "\ n ";
82}
83 tvJson. setText (s );
84} catch (JSONException e ){
85 System. out. println ("Jsons parse error! ");
86 e. printStackTrace ();
87}
88}
89}

Android content:

  • How can I jump to another activity after the android AsyncTask thread finishes running?
  • Android uploads bitmap images to the Web
  • How to package the source code after modifying the Android code
  • How to parse the JSON format that is not a key-Value Pair in Android?
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.