JSON Parsing in Android
JSON (JavaScript Object Notation) is a straightforward data exchange format to interchange the server’s data, and it is a better alternative for XML. This is because JSON is a lightweight and structured language. Android supports all the JSON classes such as JSONStringer, JSONObject, JSONArray, and all other forms to parse the JSON data and fetch the required information by the program. JSON’s main advantage is that it is a language-independent, and the JSON object will contain data like a key/value pair. In general, JSON nodes will start with a square bracket ([) or with a curly bracket ({). The square and curly bracket’s primary difference is that the square bracket ([) represents the beginning of a JSONArray node. Whereas, the curly bracket ({) represents a JSONObject. So one needs to call the appropriate method to get the data. Sometimes JSON data start with [. We then need to use the getJSONArray() method to get the data. Similarly, if it starts with {, then we need to use the getJSONobject() method. The syntax of the JSON file is as following:
{ "Name": "GeeksforGeeks", "Estd": 2009, "age": 10, "address": { "buildingAddress": "5th & 6th Floor Royal Kapsons, A- 118", "city": "Sector- 136, Noida", "state": "Uttar Pradesh (201305)", "postalCode": "201305" },
In this article, we are going to parse a JSON file in Android. Note that we are going to implement this project using the Kotlin language.
Step by Step Implementation
To parse a JSON file in Android, follow the following steps:
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the activity_main.xml file
Go to the activity_main.xml file which represents the UI of the application. Create a ListView as shown. Below is the code for the activity_main.xml file.
XML
<? xml version = "1.0" encoding = "utf-8" ?> < LinearLayout android:layout_width = "fill_parent" android:layout_height = "fill_parent" android:orientation = "vertical" > <!--This listView will display the list items--> < ListView android:id = "@+id/user_list" android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:dividerHeight = "1dp" /> </ LinearLayout > |
Step 3: Create another layout resource file
Go to app > res > layout > right-click > New > Layout Resource File and create another layout list_row.xml to show the data in the ListView. Below is the code for the list_row.xml file.
XML
<? xml version = "1.0" encoding = "utf-8" ?> < RelativeLayout android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:orientation = "horizontal" android:padding = "5dip" > <!--TextView to display the name--> < TextView android:id = "@+id/name" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:textSize = "17dp" android:textStyle = "bold" /> <!--TextView to display the designation--> < TextView android:id = "@+id/designation" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_below = "@id/name" android:layout_marginTop = "7dp" android:textColor = "#343434" android:textSize = "14dp" /> <!--TextView to display the location--> < TextView android:id = "@+id/location" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_alignBaseline = "@+id/designation" android:layout_alignBottom = "@+id/designation" android:layout_alignParentRight = "true" android:textColor = "#343434" android:textSize = "14dp" /> </ RelativeLayout > |
Step 4: Working with the MainActivity.kt file
Go to the MainActivity.kt file, and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.os.Bundle import android.util.Log import android.widget.ListAdapter import android.widget.ListView import android.widget.SimpleAdapter import androidx.appcompat.app.AppCompatActivity import org.json.JSONException import org.json.JSONObject import java.util.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super .onCreate(savedInstanceState) setContentView(R.layout.activity_main) // private string declare in the latter section of the program val jsonStr = listData try { // Create a userList string hashmap arraylist val userList = ArrayList<HashMap<String, String?>>() // Declaring the listView from the layout file val lv = findViewById<ListView>(R.id.user_list) // Initializing the JSON object and extracting the information val jObj = JSONObject(jsonStr) val jsonArry = jObj.getJSONArray( "users" ) for (i in 0 until jsonArry.length()) { val user = HashMap<String, String?>() val obj = jsonArry.getJSONObject(i) user[ "name" ] = obj.getString( "name" ) user[ "designation" ] = obj.getString( "designation" ) user[ "location" ] = obj.getString( "location" ) userList.add(user) } // ListAdapter to broadcast the information to the list elements val adapter: ListAdapter = SimpleAdapter( this , userList, R.layout.list_row, arrayOf( "name" , "designation" , "location" ), intArrayOf( R.id.name, R.id.designation, R.id.location ) ) lv.adapter = adapter } catch (ex: JSONException) { Log.e( "JsonParser Example" , "unexpected JSON exception" , ex) } } // JSON object in the form of input stream private val listData: String get() = ( "{ \"users\" :[" + "{\"name\":\"Ace\",\"designation\":\"Engineer\",\"location\":\"New York\"}" + ",{\"name\":\"Tom\",\"designation\":\"Director\",\"location\":\"Chicago\"}" + ",{\"name\":\"Tim\",\"designation\":\"Charted Accountant\",\"location\":\"Sunnyvale\"}] }" ) } |