◎위챗 : speedseoul
http://www.androiddeft.com/2017/09/10/json-parsing-android-http/
JSON (JavaScript Object Notation) is a syntax used to store and exchange data between the application and the server. It is the best alternative to XML. JSON is easy to read and understand. In this tutorial, we will learn how to retrieve JSON data from the server using HttpURLConnection, parse the JSON and display it in a customized ListVew.
Table of Contents [hide]
A JSON object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).
A JSON array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
A value can be another JSON Object, JSON array, String, Number, Boolean value or NULL.
We will be handling employee data in this tutorial. So let’s create a Java bean called EmployeeDetails inside beans package.
We will have customized List View for displaying the data.
Open activity_main.xml and add a List View.
Now create a file employee_row.xml in layout folder, which contains Text Views to display employee data.
Create a file employee_background.xml inside the drawable folder. This will provide background for each element in the list view.
In order to display the fetched JSON data from the server, we will be customizing the ArrayAdapter. Create a class EmployeeAdapter in adapter package.
We use the following methods to fetch the JSON nodes:
getJSONArray(String name) : fetches JSON array from JSON object.
getJSONObject(int index) : fetches JSON object from a JSON array.
getString(String name) : fetches String value from JSON object.
getInt(String name) : fetches Integer value from JSON object.
Any network related operations in Android needs to be performed as an asynchronous task, without disturbing the UI thread. If we perform the network operation on the main thread (UI thread) then we will get NetworkOnMainThreadException. We will be using following methods in AsyncTask:
onPreExecute() : Prerequisite operations such as displaying progress bar.
doInBackground(String… params) : Performing the network operation (calling makeHttpRequest in this tutorial).
onPostExecute(String result): Parse the response and populate the UI. We will be calling runOnUiThread(Runnable) for the same.
Below is the complete implementation of MainActivity.