我正在使用 kotlin 开发应用程序。现在我想从服务器获取 JSON 数据。
在 java 中,我实现了 Asyntask 和 Rxjava,用于从 Url 读取 JSON。我也在谷歌搜索,但我无法获得满足我要求的适当详细信息。
我如何使用 kotlin 从 Url 读取 JSON?
最佳答案
我猜您正在尝试读取来自服务器 API 的响应,您希望它是带有 JSON 的字符串。为此,您可以使用:
val apiResponse = URL("yourUrl").readText()
来自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.
请注意,如果您在 Android Activity 中使用它,应用程序会崩溃,因为您正在使用异步调用阻塞主线程。为避免应用程序崩溃,我建议您使用 Anko .更准确地说,你只需要 add the commons dependency –不是整个图书馆–。
您可以找到更多信息 in this blog post
关于android - 如何使用 kotlin Android 从 Url 读取 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44883593/