7.2.2 Android JSON Data Parsing
Category Android Basic Beginner Tutorial
Introduction to This Section:
>
I believe everyone is familiar with JSON. The data transmission method we usually use to interact with the server is mostly in the form of JSON strings. To save an object, we can also write it as a JSON string and store it! Parsing JSON, whether you use Gson, Fastjson, jackson, etc., this section will not use these third-party parsing libraries. Instead, we will use Android's built-in JSON parser to parse JSON! Alright, let's get started with this section!
1. JSON Concepts and Comparison with XML
1) What is JSON?
>
Answer: JavaScript Object Notation, a lightweight data interchange format, just like XML, widely adopted as a solution for client-server interactions! It has good readability and is easy to write quickly.
2) Comparison between JSON and XML:
>
JSON and XML have similar data readability;
JSON and XML both have rich parsing methods;
JSON has a smaller data volume compared to XML;
JSON interacts more conveniently with JavaScript;
JSON is less descriptive than XML;
JSON is much faster than XML.
PS: The above is from Baidu. Simply put, the advantages of JSON: smaller volume, saves traffic, just not as intuitive as XML, and slightly worse readability!
3) JSON Format Specification:
>
Just like a protocol, there must be a set of specifications, as both parties transmit data through JSON strings. The syntax rules are as follows: data is in name/value pairs; data is separated by commas; curly braces hold objects; square brackets hold arrays; The writing format of JSON data: name/value pairs, for example: "person": "coder-pig". Here is a simple JSON string example:
[
{ "id":"1","name":"基神","age":"18" },
{ "id":"2","name":"B神","age":"18" },
{ "id":"3","name":"曹神","age":"18" }
]
>
We can not only parse JSON but also splice JSON ourselves. Of course, if you splice a JSON string and are not sure if it's correct, you can search Baidu for a validation tool, such as: http://www.tutorialpro.org/jsontool, paste the JSON string and validate it!
2. JSON Parsing Classes Provided by Android
>
These APIs exist under the org.json package, and the classes we use include:
JSONObject: JSON object, can complete the mutual conversion between JSON string and Java object
JSONArray: JSON array, can complete the mutual conversion between JSON string and Java collection or object
JSONStringer: JSON text builder class, this class can help create JSON text quickly and conveniently, each JSONStringer entity can only correspond to creating one JSON text
JSONTokener: JSON parsing class
JSONException: JSON exception
3. Code Example: Parsing JSON String:
PS: Here we will not write a servlet or request a website, but directly write the JSON into a string for parsing, just simulate it!
1) Simple JSON String Parsing Example:
We are parsing the simple JSON above, first let's write a POJO class:
Person.java:
/**
* Created by Jay on 2015/9/8 0008.
*/
public class Person {
private String id;
private String name;
private String age;
public void setId(String id){
this.id = id;
}
public String getId(){
return this.id;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setAge(String age){
this.age = age;
}
public String getAge(){
return this.age;
}
@Override
public String toString() {
return this.name + "~年方:" + this.age;
}
}
Write a method to parse the above JSON string:
private void parseEasyJson(String json){
persons = new ArrayList<Person>();
try{
JSONArray jsonArray = new JSONArray(json);
for(int i = 0;i < jsonArray.length();i++){
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
Person person = new Person();
person.setId(i+"");
person.setName(jsonObject.getString("name"));
person.setAge(jsonObject.getString("age"));
persons.add(person);
}
}catch (Exception e){e.printStackTrace();}
}
Running Effect Image: -2.2.6 AbsoluteLayout (Absolute Layout)
-2.3.1 TextView (Text View) Detailed Explanation
-2.3.2 EditText (Input Box) Detailed Explanation
-2.3.5 RadioButton (Radio Button) & Checkbox (Checkbox)
-2.3.6 ToggleButton and Switch
-2.3.7 ProgressBar (Progress Bar)
-2.3.9 RatingBar (Star Rating Bar)
-2.4.1 ScrollView (Scroll View)
-2.4.2 Date & Time Components (Part 1)
-2.4.3 Date & Time Components (Part 2)
-2.4.5 Simple Usage of ListView
-2.4.6 BaseAdapter Optimization
-2.4.8 Solving ListView Checkbox Misalignment
-2.4.9 ListView Data Update Issues
-2.5.0 Building a Reusable Custom BaseAdapter
-2.5.1 Implementing Multi-Layout ListView Items
-2.5.2 Basic Usage of GridView (Grid View)
-2.5.3 Basic Usage of Spinner (Dropdown List)
-2.5.4 Basic Usage of AutoCompleteTextView (Auto-Complete Text View)
-2.5.5 Basic Usage of ExpandableListView (Expandable List)
-2.5.6 Basic Usage of ViewFlipper (Flip View)
-2.5.8 Detailed Explanation of Notification (Status Bar Notification)
-2.5.9 Detailed Explanation of AlertDialog (Dialog Box)
-2.6.0 Basic Usage of Other Common Dialogs
-2.6.1 Basic Usage of PopupWindow (Floating Window)
-2.6.3 Simple Usage of ViewPager
-2.6.4 Simple Usage of DrawerLayout (Official Side Sliding Menu)
-3.1.1 Event Handling Mechanism Based on Listeners
-3.2 Event Handling Mechanism Based on Callbacks
-3.3 Analysis of Handler Message Passing Mechanism
-3.4 TouchListener vs OnTouchEvent + Multi-Touch
-3.5 Listening to EditText Content Changes
-3.6 Responding to System Setting Changes (Configuration Class)
-3.7 AsyncTask Asynchronous Tasks
-4.1.1 Introduction to Activity
-4.1.2 Getting Started with Activity
-4.2.1 Introduction to Service
-4.3.1 Basic BroadcastReceiver
-4.3.2 Detailed BroadcastReceiver
-4.4.1 Introduction to ContentProvider
-4.4.2 Further Exploration of ContentProvider – Document Provider
-4.5.2 Passing Complex Data with Intent
-5.1 Basic Overview of Fragment
-5.2.1 Fragment Example - Bottom Navigation Bar Implementation (Method 1)
-5.2.2 Fragment Example - Bottom Navigation Bar Implementation (Method 2)
-5.2.3 Fragment Example - Bottom Navigation Bar Implementation (Method 3)
-5.2.4 Fragment Example - Bottom Navigation Bar + ViewPager Page Sliding
-5.2.5 Fragment Example - Simple Implementation of News (Shopping) App List Fragment
-6.1 Data Storage and Access - File Storage and Reading
-6.2 Data Storage and Access - SharedPreferences for Saving User Preferences
-6.3.1 Data Storage and Access - Introduction to SQLite Database
-6.3.2 Data Storage and Access - Further Exploration of SQLite Database
-7.1.1 Android Network Programming and HTTP Protocol Learning
-7.1.2 Android HTTP Request and Response Headers Learning
-7.1.3 Android HTTP Request Method: HttpURLConnection
-7.1.4 Android HTTP Request Method: HttpClient
-7.2.1 Android XML Data Parsing
- 7.2.2 Android JSON Data Parsing
-7.3.2 Android File Download (1)
-7.3.3 Android File Download (2)
-7.4 Android Calling WebService
-7.5.1 Basic Usage of WebView (Web View)
-7.5.2 Basic Interaction Between WebView and JavaScript
-7.5.3 Considerations for WebView in Android 4.4 and Later
- 7.5.5 WebView Cache Issues
- 7.5.6 WebView Handling Webpage Error Code Information
- 7.6.1 Socket Learning Network Basics Preparation
- 7.6.2 Socket Communication Based on TCP Protocol (1)
- 7.6.3 Socket Communication Based on TCP Protocol (2)
- 7.6.4 Socket Communication Based on UDP Protocol
- 8.1.1 Summary of 13 Drawable Types in Android Part 1
- 8.1.2 Summary of 13 Drawable Types in Android Part 2
- 8.1.3 Summary of 13 Drawable Types in Android Part 3
- 8.2.1 Bitmap (Bitmap) Comprehensive Analysis Part 1
- 8.2.2 OOM Issues Caused by Bitmap
- 8.3.1 Detailed Explanation of Three Drawing Tool Classes
- 8.3.2 Practical Examples of Drawing Classes
- 8.3.3 Paint API — MaskFilter (Mask)
- 8.3.4 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 1)
- 8.3.5 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 2)
- 8.3.6 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 3)
- 8.3.7 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 4)
- 8.3.8 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 5)
- 8.3.9 Paint API — ColorFilter (Color Filter) (1/3)
- 8.3.10 Paint API — ColorFilter (Color Filter) (2/3)
- 8.3.11 Paint API — ColorFilter (Color Filter) (3/3)
- 8.3.12 Paint API — PathEffect (Path Effect)
- 8.3.13 Paint API — Shader (Image Rendering)
- 8.3.14 Paint Enumerations/Constants and ShadowLayer Shadow Effect
- 8.3.15 Paint API — Typeface (Font Style)
- 8.3.16 Canvas API Detailed Explanation (Part 1)
- 8.3.17 Canvas API Detailed Explanation (Part 2) Clipping Methods Collection
- 8.3.18 Canvas API Detailed Explanation (Part 3) Matrix and drawBitmapMesh
- 8.4.1 Frame Animation in Android Animation Collection
- 8.4.2 Tween Animation in Android Animation Collection
- 8.4.3 Property Animation in Android Animation Collection - First Encounter
- 8.4.4 Property Animation in Android Animation Collection - Second Encounter
- 9.1 Playing Sound Effects with SoundPool (Duang~)
- 9.2 MediaPlayer Playing Audio and Video
- 9.3 Using Camera to Take Photos
- 9.4 Using MediaRecord to Record Audio
- 10.1 TelephonyManager (Telephone Manager)
- 10.2 SmsManager (SMS Manager)
- 10.3 AudioManager (Audio Manager)
- 10.4 Vibrator (Vibrator)
- 10.5 AlarmManager (Alarm Service)
- 10.6 PowerManager (Power Service)
- 10.7 WindowManager (Window Management Service)
- 10.8 LayoutInflater (Layout Service)
- 10.9 WallpaperManager (Wallpaper Manager)
- 10.10 Sensor Topic (1) — Introduction
- 10.11 Sensor Topic (2) — Orientation Sensor
- 10.12 Sensor Topic (3) — Accelerometer/Gyroscope Sensor
- 10.12 Sensor Topic (4) — Understanding Other Sensors
- 10.14 Android GPS Introduction
- 11.0 "2015 Latest Android Basic Beginner's Tutorial" Completion Celebration~
- 12.1 Android Exercise: DrySister Viewing Girls Application (First Edition) — Project Setup and Simple Implementation
- 12.2 DrySister Viewing Girls Application (First Edition) — 2. Parsing Backend Data
- 12.3 DrySister Viewing Girls Application (First Edition) — 3. Image Loading Optimization (Writing a Small Image Cache Framework)
- 12.4 DrySister Viewing Girls Application (First Edition) — 4. Adding Data Caching (Introducing SQLite)
- 12.5 DrySister Viewing Girls Application (First Edition) — 5. Code Review, Adjustment, and Logging Class Writing
- 12.6 DrySister Viewing Girls Application (First Edition) — 6. Icon Creation, Obfuscation, Signing, Packaging, APK Thinning, Application Release