kotlin json_Kotlin中用于获取json的改造的基本用法

本文介绍了如何在Kotlin中使用JSON,通过改造的方式获取和处理JSON数据,内容源自一篇关于Retrofit在Kotlin中获取JSON的基本用法的翻译。
摘要由CSDN通过智能技术生成

kotlin json

Welcome to a brand new tutorial for Easy Android Programming. In the tutorial, we are going to learn about the basic usage of retrofit in kotlin for fetching JSON from a remote server.

欢迎使用全新的Easy Android编程教程。 在本教程中,我们将学习kotlin中从远程服务器获取JSON的改造的基本用法。

Before starting the tutorial, I would like to tell you, code for the blog is available at Open source Github repository.

在开始本教程之前,我想告诉您,该博客的代码可在开源Github 存储库中找到

指数 (Index)

Below is the index for various sections of the blog

以下是博客各个部分的索引

  1. Motivation

    动机
  2. Process

    处理
  3. File Organization

    文件组织
  4. Movie.kt

    电影.kt
  5. MoviesResponse.kt

    电影响应
  6. MoviesService.kt

    电影服务
  7. MainActivity.kt

    MainActivity.kt
  8. Conclusion

    结论

动机 (Motivation)

I would like to quote here, a famous saying by Mr. Charles R Swindoll,

我想在这里引用查尔斯·斯温多尔先生的一句名言:

Life is 10% what happens to you and 90% how you react to it.

生活是您所发生的事情的10%,是您对它的React的90%。

处理 (Process)

So how the quote in the last section, pertains to the topic we are going to learn. We can always use our old friend Asynctasks to make networking calls rather than using a networking library like Retrofit.

因此,上一节中的引用与我们将要学习的主题有关。 我们总是可以使用我们的老朋友Asynctasks进行网络调用,而不是使用Retrofit之类的网络库。

But when we use retrofit I get below advantages

但是,当我们使用改造时,我会失去以下优势

  • Less line of Code, so clean code which Easy code maintenance for your app in future

    更少的代码行,因此干净的代码可为您的应用轻松维护代码
  • Time of Execution is one of the areas, where retrofit really shines.

    执行时间是改造真正发亮的领域之一。

There are several other benefits of using retrofit but let’s stick to the topic.

使用改造还有其他几个好处,但让我们坚持下去。

文件组织 (File Organization)

Image for post
Android Studio Screenshot
Android Studio屏幕截图

Now comes the implementation part, In your module-level build.gradle file you need to add retrofit, and related gson-converter libraries as dependencies.

现在是实现部分,您需要在模块级build.gradle文件中添加改造以及相关的gson-converter库作为依赖项。

// retrofit
implementation 'com.squareup.retrofit2:retrofit:2.0.0'
implementation 'com.squareup.retrofit2:converter-gson:2.0.0'

After completing the Gradle sync in your project, you will be ready for using retrofit in your project.

在项目中完成Gradle同步后,您就可以在项目中使用改造了。

Once this is done, we need to add a few more files like a service interface ( Please don’t get confused with Android Services). These are the files that we require

完成此操作后,我们需要添加更多文件,例如服务界面(请不要与Android Services混淆)。 这些是我们需要的文件

  • Movie (A model class to hold data pertaining to each movie)

    电影(用于保存与每个电影有关的数据的模型类)
  • MoviesResponse.kt (A model class to hold data pertaining to each movie)

    MoviesResponse.kt(用于保存与每个电影有关的数据的模型类)
  • MoviesService.kt ( A class that responsible for interacting with REST HTTP URL)

    MoviesService.kt(负责与REST HTTP URL交互的类)

电影.kt (Movie.kt)

We will be using https://www.relsellglobal.in/tutorial_blogs/movies.php?year=2001.

我们将使用https://www.relsellglobal.in/tutorial_blogs/movies.php?year=2001

Let’s open this URL and we will see JSON code written below

打开此URL,我们将看到下面编写的JSON代码

{
moviesArr: [
{
name: "Om Namah sivah",
year: "2001"
},
{
name: "Jai santoshi ma",
year: "2001"
},
{
name: "Jai veer hanumaan",
year: "2001"
}
]
}

Basically, on hitting the URL we got a JSON Response that shows a list of movies in 2001. But we are going to create a mapping object/model which can hold data for a particular movie.

基本上,在访问URL时,我们得到了一个JSON响应,其中显示了2001年的电影列表。但是,我们将创建一个映射对象/模型,该对象/模型可以保存特定电影的数据。

Please focus on the code snippet

请关注代码段

{
name: "Om Namah sivah",
year: "2001"
}

So we can create a model class in kotlin mapping above JSON. it may be like below

因此,我们可以在JSON上方的kotlin映射中创建模型类。 它可能像下面

class Movie{
@SerializedName("name")
var name = ""
@SerializedName("year")
var year = ""
}

电影响应 (MoviesResponse.kt)

After the addition of Movies Model class, we need to add a class that will be used for holding the JSON Data in the right format. MoviesResponse class will be assisted by Movie objects. If we see response JSON, we will find moviesArray holds different movie JSON Objects. Hence in kotlin, we write the below code.

在添加Movies Model类之后,我们需要添加一个类,该类将用于以正确的格式保存JSON数据。 MoviesResponse类将由Movie对象辅助。 如果看到响应JSON,我们会发现filmsArray持有不同的电影JSON对象。 因此,在kotlin中,我们编写以下代码。

class MoviesResponse {
@SerializedName("moviesArr")
var moviesArr = ArrayList<Movie>()
}

电影服务 (MoviesService.kt)

As discussed earlier also, we need to add a service interface to assist the app in querying the REST HTTP URL. So in MoviesService.kt file add code for it

同样如前所述,我们需要添加一个服务接口来协助应用查询REST HTTP URL。 因此,在MoviesService.kt文件中为其添加代码

interface MoviesService {
@GET("movies.php?")
fun getMoviesList(@Query("year") year : String) : Call<MoviesResponse>
}

We are making an HTTP GET request for fetching data from URL, by passing year as a query string parameter.

我们正在通过将year作为查询字符串参数传递一个HTTP GET请求,以从URL提取数据。

MainActivity.kt (MainActivity.kt)

Let’s open your MainActivity.kt file

打开您的MainActivity.kt文件

add an instance variable,

添加一个实例变量,

var BaseUrl = "https://www.relsellglobal.in/tutorial_blogs/"

Inside your oncreate method, add below line to create an instance of retrofit using builder for the base Url.

在您的oncreate方法中,添加以下行以使用构建器为基本Url创建改造实例。

val retrofit = Retrofit.Builder()
.baseUrl(BaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build()

Now we need to create an instance of MovieService

现在我们需要创建一个MovieService实例

val service = retrofit.create(MoviesService::class.java)

Then we will call the respective method declared in the service class, passing a param

然后,我们将调用服务类中声明的相应方法,并传递一个参数

val call = service.getMoviesList("2000")        call.enqueue(object : Callback<MoviesResponse> {
override fun onResponse(call: Call<MoviesResponse>, response: Response<MoviesResponse>) {
if (response.code() == 200) {
val movieResponse = response.body()!!
for( movie in movieResponse.moviesArr){
Log.v("MainActivity", movie.name)
}
}
}
override fun onFailure(call: Call<MoviesResponse>, t: Throwable) { }
})

So, in the logcat in the android studio, we will see debug statements for different movies name as received from JSON.

因此,在android studio的logcat中,我们将看到从JSON接收的不同电影名称的调试语句。

结论 (Conclusion)

This brings us to the end of the blog about the basic usage of Retrofit in Kotlin. A video tutorial for the blog will be available very soon. I Will update the link here.

这使我们结束了有关Kotlin中Retrofit的基本用法的博客结尾。 该博客的视频教程即将推出。 我将在此处更新链接。

Thanks for reading.

谢谢阅读。

Happy Coding.

编码愉快。

翻译自: https://medium.com/swlh/basic-usage-of-retrofit-in-kotlin-for-fetching-json-8b9d37999058

kotlin json

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值