The Wayback Machine - https://web.archive.org/web/20241109165540/https://www.geeksforgeeks.org/android-json-parsing-using-retrofit-library-with-jetpack-compose/
Open In App

Android – JSON Parsing Using Retrofit Library with Jetpack Compose

Last Updated : 30 Jun, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JSON is a format with the help of which we can exchange the data from the server within our application or a website. For accessing this data from the server within android applications. There are several libraries that are available such as Volley and Retrofit. In this article, we will take a look at JSON Parsing in Android applications using Jetpack Compose. 

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Adding dependency for using Retrofit

Navigate to app > Gradle Scripts > build.gradle file and add the below dependency to it. Comments are added to the code.

// below dependency for using retrofit.
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'

// below dependency for using picasso image loading library
implementation 'com.squareup.picasso:picasso:2.71828'

After adding this dependency simply sync your project to install it.

Step 3: Adding a new color in the Color.kt file

Navigate to app > java > your app’s package name > ui.theme > Color.kt file and add the below code to it.   

Kotlin




package com.example.newcanaryproject.ui.theme
  
import androidx.compose.ui.graphics.Color
  
val Purple200 = Color(0xFF0F9D58)
val Purple500 = Color(0xFF0F9D58)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
  
// on below line we are adding different colors.
val greenColor = Color(0xFF0F9D58)


Step 4: Adding permissions to the internet in the AndroidManifest.xml file

Navigate to the app > AndroidManifest.xml and add the below code to it.  

XML




<!--permissions for INTERNET-->
<uses-permission android:name="android.permission.INTERNET"/>


Step 5: Creating a Modal class

Navigate to app > java > your app’s package name > Right-click on it > New > Kotlin class and specify the name of the class as CourseDataModal and add the below code to it. Comments are added in the code to get to know in detail. 

Kotlin




package com.example.newcanaryproject
  
data class CourseDataModal(
    // on below line creating variables for our modal class
    // make sure that variable name should be same to
    // that of key which is used in json response.
    var courseName: String,
    var courseimg: String,
    var courseDesc: String,
    var Prerequisites: String,
    var courseLink: String
)


Step 6: Creating an Interface

Navigate to app > java > your app’s package name > Right-click on it > New > Kotlin class and select interface in it and then specify the name as RetrofitAPI. Add the below code to it. Comments are added in the code to get to know in detail. 

Kotlin




package com.example.newcanaryproject
  
import retrofit2.Call
import retrofit2.http.GET
  
interface RetrofitAPI {
    // as we are making get request
    // so we are displaying GET as annotation.
    // and inside we are passing
    // last parameter for our url.
    @GET("8RFY")
    fun  // as we are calling data from array
    // so we are calling it with json object
    // and naming that method as getCourse();
            getCourse(): Call<CourseDataModal?>?
}


Step 7: Working with the MainActivity.kt file

Navigate to app>java>your app’s package name>MainActivity.kt file and add the below code to it. Comments are added in the code to get to know in detail. 

Kotlin




package com.example.newcanaryproject
  
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.*
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.*
import coil.compose.rememberAsyncImagePainter
import com.example.newcanaryproject.ui.theme.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
  
class MainActivity : ComponentActivity() {
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            NewCanaryProjectTheme {
                // on below line we are specifying background color for our application
                Surface(
                    // on below line we are specifying modifier and color for our app
                    modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background
                ) {
  
                    // on below line we are specifying theme as scaffold.
                    Scaffold(
  
                        // in scaffold we are specifying top bar.
                        topBar = {
  
                            // inside top bar we are specifying background color.
                            TopAppBar(backgroundColor = greenColor,
  
                                // along with that we are specifying title 
                                // for our top bar.
                                title = {
  
                                    // in the top bar we are specifying tile as a text
                                    Text(
  
                                        // on below line we are specifying 
                                        // text to display in top app bar.
                                        text = "JSON Parsing in Android",
  
                                        // on below line we are specifying 
                                        // modifier to fill max width.
                                        modifier = Modifier.fillMaxWidth(),
  
                                        // on below line we are specifying 
                                        // text alignment.
                                        textAlign = TextAlign.Center,
  
                                        // on below line we are specifying 
                                        // color for our text.
                                        color = Color.White
                                    )
                                })
                        }) {
                        // on below line we are calling pop window 
                        // dialog method to display ui.
                        volleyJSONParsing()
                    }
                }
            }
        }
    }
}
  
// on below line we are creating a
// pop up window dialog method
@Composable
fun volleyJSONParsing() {
    val ctx = LocalContext.current
    // on below line we are creating variables.
    val courseName = remember {
        mutableStateOf("")
    }
    val courseRequisites = remember {
        mutableStateOf("")
    }
    val courseImg = remember {
        mutableStateOf("")
    }
    val courseDesc = remember {
        mutableStateOf("")
    }
    val courseLink = remember {
        mutableStateOf("")
    }
    val progress = remember {
        mutableStateOf(true)
    }
  
    jsonParsing(ctx, courseName, courseRequisites, courseImg, courseDesc, courseLink, progress)
  
    // on the below line we are creating a column.
    Column(
        // in this column we are specifying
        // modifier to add padding and fill
        // max size
        modifier = Modifier
            .fillMaxSize()
            .padding(horizontal = 20.dp),
  
        // on below line we are adding horizontal alignment
        // and vertical arrangement
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Top
    ) {
  
        // on below line we are creating a column.
        if (progress.value) {
            Column(
                // in this column we are specifying
                // modifier to add padding and fill
                // max size
                modifier = Modifier
                    .fillMaxSize()
                    .padding(horizontal = 20.dp),
  
                // on below line we are adding horizontal alignment
                // and vertical arrangement
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                // below line is use to display a circular progress bar.
                CircularProgressIndicator(
                    // below line is use to add padding to our progress bar.
                    modifier = Modifier.padding(16.dp),
  
                    // below line is use to add color to our progress bar.
                    color = colorResource(id = R.color.purple_200),
  
                    // below line is use to add stroke width to our progress bar.
                    strokeWidth = Dp(value = 4F)
                )
            }
        }
  
        // on the below line we are adding a spacer.
        Spacer(modifier = Modifier.height(4.dp))
  
        // on below line we are adding image for our image view.
        Image(
            // on below line we are adding the image url
            // from which we will  be loading our image.
            painter = rememberAsyncImagePainter(courseImg.value),
  
            // on below line we are adding content
            // description for our image.
            contentDescription = "gfg image",
  
            // on below line we are adding modifier for our
            // image as wrap content for height and width.
            modifier = Modifier
                .wrapContentSize()
                .wrapContentHeight()
                .fillMaxWidth()
                .padding(4.dp),
            alignment = Alignment.Center
        )
  
        // on the below line we are adding a spacer.
        Spacer(modifier = Modifier.height(10.dp))
  
        // on below line we are creating
        // text for course name.
        Text(
            text = courseName.value,
            modifier = Modifier.fillMaxWidth(),
            color = Color.Black,
            fontSize = 20.sp,
            fontFamily = FontFamily.Default,
            fontWeight = FontWeight.Bold, textAlign = TextAlign.Center
        )
  
        // on below line we are adding spacer
        Spacer(modifier = Modifier.height(20.dp))
  
        // on below line we are adding
        // text for course prerequisites
        Text(
            text = courseRequisites.value,
            modifier = Modifier.fillMaxWidth(),
            color = Color.Black,
            fontSize = 16.sp,
            fontFamily = FontFamily.Default,
            fontWeight = FontWeight.Normal, textAlign = TextAlign.Center
        )
  
        // on below line we are adding spacer
        Spacer(modifier = Modifier.height(30.dp))
  
        // on below line we are creating a
        // text for our description.
        Text(
            text = courseDesc.value,
            modifier = Modifier.fillMaxWidth(),
            color = Color.Black,
            fontSize = 15.sp,
            fontFamily = FontFamily.Default,
            fontWeight = FontWeight.Normal, textAlign = TextAlign.Start
        )
  
        // on the below line we are creating a column.
        Column(
            // in this column we are specifying
            // modifier to add padding and fill
            // max size
            modifier = Modifier
                .fillMaxSize(),
            // on below line we are adding horizontal alignment
            // and vertical arrangement
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Bottom
        ) {
            // on below line we are creating a button
            Button(
                onClick = {
                    // on below line we are opening
                    // a intent to view the url.
                    val i = Intent(Intent.ACTION_VIEW)
                    i.setData(Uri.parse(courseLink.value))
                    ctx.startActivity(i)
                },
                // on below line we are
                // adding modifier for our button.
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(3.dp)
                    .align(Alignment.CenterHorizontally)
                    .fillMaxWidth()
            ) {
                // on below line we are setting text as visit course
                Text(text = "Visit Course", color = Color.White)
            }
        }
  
    }
}
  
fun jsonParsing(
    ctx: Context,
    name: MutableState<String>,
    requisites: MutableState<String>,
    Img: MutableState<String>,
    Desc: MutableState<String>,
    Link: MutableState<String>,
    progress: MutableState<Boolean>,
) {
  
    // on below line we are creating a retrofit
    // builder and passing our base url
    // on below line we are creating a retrofit
    // builder and passing our base url
    val retrofit = Retrofit.Builder()
        .baseUrl("https://jsonkeeper.com/b/")
  
        // on below line we are calling add Converter
        // factory as GSON converter factory.
        // at last we are building our retrofit builder.
        .addConverterFactory(GsonConverterFactory.create())
        .build()
  
    // below line is to create an instance for our retrofit api class.
    // below line is to create an instance for our retrofit api class.
    val retrofitAPI = retrofit.create(RetrofitAPI::class.java)
  
    val call: Call<CourseDataModal?>? = retrofitAPI.getCourse()
  
    // on below line we are making a call.
    call!!.enqueue(object : Callback<CourseDataModal?> {
        override fun onResponse(
            call: Call<CourseDataModal?>?,
            response: Response<CourseDataModal?>
        ) {
            if (response.isSuccessful()) {
                // inside the on response method.
                // on below line we are getting data from our response
                // and setting it in variables.
                val courseName: String = response.body()!!.courseName
                val courseLink: String = response.body()!!.courseLink
                val courseImg: String = response.body()!!.courseimg
                val courseDesc: String = response.body()!!.courseDesc
                val coursePreq: String = response.body()!!.Prerequisites
  
                progress.value = !progress.value
                // on below line we are setting
                // our data to our variables
                name.value = courseName
                Link.value = courseLink
                Img.value = courseImg
                Desc.value = courseDesc
                requisites.value = coursePreq
  
            }
        }
  
        override fun onFailure(call: Call<CourseDataModal?>?, t: Throwable?) {
            // displaying an error message in toast
            Toast.makeText(ctx, "Fail to get the data..", Toast.LENGTH_SHORT)
                .show()
        }
    })
}


Now run your application to see the output of it. 

Output:



Similar Reads

Android - Extract Data From JSON Array using Retrofit Library with Jetpack Compose
JSON responses are of 2 types i.e. JSON Object and JSON Array. JSON Array consists of individual JSON objects which are having same similar structure but have different values within it. JSON Array is used to parse the data in the form of a list or an array. In the previous article, we have taken a look at How to extract data from JSON Object in An
6 min read
Android - JSON Parsing using Volley Library with Jetpack Compose
JSON is a JavaScript object notation which is a format to exchange the data from the server. JSON stores the data in a lightweight format. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specifically take a look at the implementation of JsonObject using Volley in Android
8 min read
JSON Parsing in Android using Retrofit Library
JSON is also known as (JavaScript Object Notation) is a format to exchange the data from the server. The data stored in JSON format is lightweight and easy to handle. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specifically take a look at the implementation of JsonOb
6 min read
Android - JSON Parsing using Retrofit Library with Kotlin
JSON is a format with the help of which we can exchange the data from the server within our application or a website. For accessing this data from the server within android applications. There are several libraries that are available such as Volley and Retrofit. In this article, we will take a look at JSON Parsing in Android applications using Kotl
6 min read
How to Update Data in API using Retrofit in Android using Jetpack Compose?
Android applications use APIs within Android Applications to access data from databases. We can perform several operations using APIs such as Reading, Writing, and Updating our Data in the Database. In this article, we will take a look at How to Update Data in API using Retrofit in Android using Jetpack Compose. Note: If you are seeking Java code f
9 min read
How to Post Data to API using Retrofit in Android using Jetpack Compose?
APIs are used within Android Applications to interact with databases to perform various CRUD operations on data within the database such as adding new data, reading the existing data, and updating and deleting existing data. In this article, we will take a look at How to Post Data to API using Retrofit in Android using Jetpack Compose. Note: If you
9 min read
Android - Extract Data From JSON Array using Volley Library with Jetpack Compose
JSON responses are of 2 types i.e. JSON Object and JSON Array. JSON Array consists of individual JSON objects which are having same similar structure but have different values within it. JSON Array is used to parse the data in the form of a list or an array. In the previous article, we have taken a look at How to extract data from JSON Object in An
5 min read
How to Extract Data from JSON Array in Android using Retrofit Library?
In the previous article on JSON Parsing in Android using Retrofit Library, we have seen how we can get the data from JSON Object in our android app and display that JSON Object in our app. In this article, we will take a look at How to extract data from JSON Array and display that in our app. Note: To extract Data from JSON Array in Android using V
9 min read
Android - Extract Data From JSON Array using Retrofit Library with Kotlin
In the android application, the response from the server is in the form of JSON. We can get to see either a JSON Array or a JSON Object in the response. JSON Array is the list of data which is having similar JSON objects. In the previous article, we have taken a look at How to parse data from JSON Object in android applications using Kotlin. In thi
7 min read
Android Jetpack Compose - Interoperability Using Compose in XML Layouts
Writing UI in jetpack compose can be fun, but can be difficult to migrate your whole project into Compose at one time. Fortunately, Jetpack Compose provides Interoperability api to use compose in existing XML views so that you can migrate to compose slowly. Prerequisites: Knowledge of Jetpack Compose.Knowledge of KotlinKnowledge of Android’s View.
3 min read
JSON Parsing in Android using Volley Library
JSON is also known as (JavaScript Object Notation) is a format to exchange the data from the server. The data stored in JSON format is lightweight and easy to handle. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specifically take a look at the implementation of JsonOb
6 min read
JSON Parsing in Android Using Volley Library with Kotlin
JSON is a JavaScript object notation which is a format to exchange the data from the server. JSON stores the data in a lightweight format. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specifically take a look at the implementation of JsonObject using Volley in Android
5 min read
How to GET Data From API using Retrofit Library in Android?
A GET request is one of the HTTP request methods that can be used to retrieve data from a server. In an API context, a GET request is typically used to retrieve a specific resource or a collection of resources from a server. When a client makes a GET request to a server, it sends a request message that contains the URL of the desired resource along
7 min read
Android - POST Raw Whole JSON in the Body of a Retrofit Request
REST APIs provide us a functionality with the help of which we can add data to our database using REST API. For posting this data to our database we have to use the Post method of REST API to post our data. We can post data to our API in different formats. In this article, we will take a look at How to Post raw whole JSON in the body of a Retrofit
8 min read
Android Runtime Permissions with Dexter using Android Jetpack Compose
Android applications require the usage of hardware devices within the android applications such as microphones or cameras. For using these devices within any android application. Permissions for using this hardware have to be provided to the application. For giving these permissions to the application runtime permissions are used. Handling permissi
7 min read
Start a New Activity using Intent in Android using Jetpack Compose
In Android OS, an Intent is a mechanism used to navigate a user to another activity or application to achieve a specific task. In general, Intents are used to progress to the next activity or come back to the previous activity. In this article, we will show you how you could start a New Activity using Intent in Android using Jetpack Compose. Follow
4 min read
How to Post Data to API using Volley in Android using Jetpack Compose?
APIs are used within Android Applications to interact with a database to perform various CRUD operations on data within the database such as adding new data, reading the existing data, and updating and deleting existing data. In this article, we will take a look at How to Post data to API in android using Volley in Jetpack Compose. Note: If you are
9 min read
Horizontal ListView in Android using Jetpack Compose
Many Android Applications present data in the form of horizontally scrollable lists. This list can be scrolled horizontally. In this article, we will take a look at How to Implement Horizontal ListView in Android Applications using Jetpack Compose. Note: If you are seeking Java code for Jetpack Compose, please note that Jetpack Compose is only avai
6 min read
Material Design Text Input Field using Jetpack Compose in Android
Jetpack Compose is a modern toolkit for building native Android UI. Jetpack Compose simplifies and accelerates UI development on Android with less code, powerful tools, and intuitive Kotlin APIs. Compose is built to support material design principles. Many of its UI elements implement material design out of the box. In this article, we will explain
3 min read
How to Remove TextField Padding in Android using Jetpack Compose?
In Android Jetpack Compose, a TextField is used to take input from the user in the form of text. TextField when in focus or when clicked invokes a soft keyboard. In general, TextField is highly attributed for a better feel and appearance. However, we can use a pre-developed TextField, named BasicTextField, which has no attributes like that of a reg
3 min read
WebView in Android using Jetpack Compose
In Android, a WebView is an extension of View Class that allows us to display webpages. In simpler words, if you want to display a webpage in Activity Layout, then you can implement a WebView to display it. It is very similar to a browser but isn't one. A WebView can rather be referred to as a show or a preview of a browser as it lacks most functio
3 min read
Play Audio in Android using Jetpack Compose
In Android, a MediaPlayer is used to play media files like audio and video files in the application. The MediaPlayer Class uses the MediaPlayer API for performing various functions like creating a MediaPlayer, playing, pausing, starting, and stopping the media. In this article, we will show you how you could play an Audio File on Android using Jetp
3 min read
Curved Text in Android using Jetpack Compose
In Android, there are no inbuilt schemes to implement designed text like the word art, which is available in applications like MS Word. We can always refer to or download such schemes like designed font faces to implement designed text. However, it is also possible to natively build (building from scratch) such designed texts in an Android Project.
3 min read
How to Get Screen Width and Height in Android using Jetpack Compose?
Android applications are being developed for different device orientations to support a huge range of devices. So that users with different device size configurations can use the application. Many applications need to get the height and width of the device screen to create UI. In this article, we will take a look at How to get Screen Width and Heig
5 min read
Extract Data From PDF File using Android Jetpack Compose
PDF files are used in many android applications for displaying data in the form of images, text as well as graphics. Many applications are also required to get the data from this PDF file and display this data within the android application. So for extracting the data from PDF file pdf reader is used which is used to read pdf and get the data from
6 min read
TopAppBar in Android using Jetpack Compose
TopAppBar is similar to that of the Action Bar widget in Android. This is one of the most UI components in Android. The action bar is used to represent the app name and action items in Android. In this article, we will take a look at the implementation of the TopAppBar in Android using Jetpack compose. Attributes of Top App Bar WidgetAttributes Des
3 min read
How to Draw Track on Google Maps in Android using Jetpack Compose?
In many android apps, we have seen that there is a route marker from a source location to the destination location. In this article, we will take a look at How we can draw a track on Google Maps in Android using Jetpack Compose. Step By Step ImplementationStep 1: Create a New Project in Android StudioTo create a new project in Android Studio please
6 min read
Material Design Buttons using Jetpack Compose in Android
Jetpack Compose is a modern toolkit for building native Android UI. Jetpack Compose simplifies and accelerates UI development on Android with less code, powerful tools, and intuitive Kotlin APIs. Compose is built to support material design principles. Many of its UI elements implement material design out of the box. In this article, we will explain
4 min read
Custom Chips using Jetpack Compose in Android
Chips in android are one of the components which are used to make the choice filters, actions, and display the selectable options in the compact area of the Android Window. In this article, we will use Android's Jetpack Compose to create those chips. A sample image is given below to give an idea of what we are going to build. Note that we are going
5 min read
How to make Text Selectable in Android using Jetpack Compose?
By default, Composable Texts are not selectable which means users cannot copy text from your application, and to enable text selection you need to wrap the text elements into Selection Container. In this article, we will use Android’s Jetpack Compose to create those chips. A sample image is given below to give an idea of what we are going to build.
2 min read
three90RightbarBannerImg