如何使用kotlin Android从Url读取JSON? [英] How to read JSON from Url using kotlin Android?

查看:498
本文介绍了如何使用kotlin Android从Url读取JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用kotlin开发应用程序.现在我想从服务器获取JSON数据.

在Java中,已实现Asyntask以及Rxjava以便从Url读取JSON.我也在Google中搜索,但我无法获得符合我要求的详细信息.

如何使用Kotlin从Url读取JSON?

解决方案

我猜您正在尝试从服务器API读取响应,您希望该API是带有JSON的字符串.为此,您可以使用:

val apiResponse = URL("yourUrl").readText()

来自文档:

使用UTF-8或指定的字符集以字符串形式读取此URL的全部内容.

不建议在大文件上使用此方法.

请注意,如果您在Android活动中使用此功能,则应用程序将崩溃,因为您使用异步调用阻止了主线程.为避免应用崩溃,我建议您使用 Anko .更准确地说,您只需添加公共依赖项 –而不是整个库–. /p>

您可以在此博客文章中找到更多信息

Am using kotlin for developing the application.Now i want to get JSON data from server.

In java am implemented Asyntask as well as Rxjava for read JSON from Url . Am also search in google but i cant get proper details for my requirement.

How can i read JSON from Url using kotlin?

解决方案

I guess you're trying to read the response from a server API, which you expect to be a string with JSON. To do so, you can use:

val apiResponse = URL("yourUrl").readText()

From the docs:

Reads the entire content of this URL as a String using UTF-8 or the specified charset.

This method is not recommended on huge files.

Note that, if you're using this inside an Android activity, the app crashes because you're blocking the main thread with an async call. To avoid the app from crashing, I recommend you use Anko. More precisely, you just have to add the commons dependency –not the entire library–.

You can find more info in this blog post

这篇关于如何使用kotlin Android从Url读取JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆