Android – 使用带有 Jetpack Compose 的 Retrofit 库进行 JSON 解析

Posted 码农乐园

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android – 使用带有 Jetpack Compose 的 Retrofit 库进行 JSON 解析相关的知识,希望对你有一定的参考价值。

JSON 是一种格式,借助它我们可以在我们的应用程序或网站中交换来自服务器的数据。用于在 android 应用程序中从服务器访问这些数据。有几个可用的库,例如 Volley 和 Retrofit。在本文中,我们将了解使用Jetpack Compose在 Android 应用程序中进行 JSON 解析。 

分步实施

第 1 步:在 Android Studio 中创建一个新项目

要在 Android Studio 中创建新项目,请参阅如何在 Android Studio 中创建/启动新项目。选择模板时,选择Empty Compose Activity。如果您没有找到此模板,请尝试将 Android Studio 升级到最新版本。我们在 Kotlin 中演示了该应用程序,因此请确保在创建新项目时选择Kotlin作为主要语言。

第 2 步:添加使用 Retrofit 的依赖项

导航到 app > Gradle Scripts > build.gradle 文件并添加以下依赖项。注释被添加到代码中。

// 下面依赖使用改造。实施 'com.squareup.retrofit2:retrofit:2.9.0'实施 'com.squareup.retrofit2:converter-gson:2.5.0'// 下面是使用 picasso 图片加载库的依赖实施 'com.squareup.picasso:picasso:2.71828'

添加此依赖项后,只需同步您的项目即可安装它。

第 3 步:在 Color.kt 文件中添加新颜色

导航到 app > java > your app's package name > ui.theme > Color.kt 文件并将以下代码添加到其中。  

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)

第 4 步:在 AndroidManifest.xml 文件中添加互联网权限

导航到应用程序 > AndroidManifest.xml 并将以下代码添加到其中。  

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

第 5 步:创建模态类

导航到 app > java > your app's package name > 右键单击它 > New > Kotlin 类并将类的名称指定为 CourseDataModal 并将以下代码添加到其中。代码中添加注释以便详细了解。 

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
)

第 6 步:创建接口

导航到 app > java > 你的应用程序包名称 > 右键单击它 > 新建 > Kotlin 类并在其中选择接口,然后将名称指定为 RetrofitAPI。将以下代码添加到其中。代码中添加注释以便详细了解。 

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?>?

第 7 步:使用 MainActivity.kt 文件

导航到 app>java>your app's package name>MainActivity.kt 文件并将以下代码添加到其中。代码中添加注释以便详细了解。 

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()
        
    )

以上是关于Android – 使用带有 Jetpack Compose 的 Retrofit 库进行 JSON 解析的主要内容,如果未能解决你的问题,请参考以下文章

Android – 使用带有 Jetpack Compose 的 Retrofit 库进行 JSON 解析

Android Jetpack Compose 能够在每个项目上创建带有交互式按钮和值的列表吗?

Android Jetpack导航,另一个主机片段内的主机片段

告别XML,Android新声明式UI框架《Jetpack Compose入门到精通》最全开发指南

在jetpack compose中画一条线

Android Jetpack Compose 中的文本渐变