我正在使用 kotlin 开发应用程序。现在我想从服务器获取 JSON 数据。
在 java 中,我实现了 Asyntask 以及 Rxjava,用于从 Url 读取 JSON。我也在谷歌搜索,但我无法获得适合我要求的详细信息。
如何使用 kotlin 从 Url 读取 JSON?
readText() 是 Antonio Leiva 在他的 Kotlin for Android Developers 一书中介绍网络时使用的方法(以及根据dgrcode的回答在博客文章中)但是我不确定 readText() 是否是正确的方法用于从 URL 请求 JSON 响应,因为响应可能非常大(甚至 Antonio 提到确认 Kotlin 文档说 readText 有大小限制的事实)。根据这个讨论,您应该使用流而不是 readText。我希望看到使用该方法或 Kotlin 中最简洁和最佳的方法对此答案的响应,而不添加库依赖项。
另请参阅此线程
还要注意,当readtext()不是适当的选择时,安东尼奥确实在该博客文章中提供了替代方案。我很乐意看到有人提供一些关于何时合适或不合适的说明。
尝试这个
fun parse(json: String): JSONObject? {
var jsonObject: JSONObject? = null
try {
jsonObject = JSONObject(json)
} catch (e: JSONException) {
e.printStackTrace()
}
return jsonObject
}
终于从这里得到答案
使用 Retrofit 2.0 RxJava、RxAndroid、Kotlin Android Extensions 读取 Json 数据。
fun provideRetrofit(): Retrofit {
return Retrofit.Builder()
.baseUrl("https://www.example.com")
.addConverterFactory(MoshiConverterFactory.create())
.build()
}
模块
interface Api {
@GET("/top.json")
fun getTop(@Query("after") after: String,
@Query("limit") limit: String): Call<NewsResponse>;
}
我有一个 fragment_X(类 + 布局),我想在其中读取在线 Json 文件(您也可以读取 txt 文件),并将内容显示给 TextView。
==> 注意:赋予应用程序在 Manifest 中访问互联网的权利。
class Fragment_X: Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_X, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if(isNetworkAvailable()) {
val myRunnable = Conn(mHandler)
val myThread = Thread(myRunnable)
myThread.start()
}
}
// create a handle to add message
private val mHandler: Handler = object : Handler(Looper.getMainLooper()) {
override fun handleMessage(inputMessage: Message) { if (inputMessage.what == 0) {
textView.text = inputMessage.obj.toString() }
} }
// first, check if network is available.
private fun isNetworkAvailable(): Boolean { val cm = requireActivity().getSystemService(
Context.CONNECTIVITY_SERVICE
) as ConnectivityManager
return cm.activeNetworkInfo?.isConnected == true
}
//create a worker with a Handler as parameter
class Conn(mHand: Handler): Runnable {
val myHandler = mHand
override fun run() {
var content = StringBuilder()
try {
// declare URL to text file, create a connection to it and put into stream.
val myUrl = URL("http:.........json") // or URL to txt file
val urlConnection = myUrl.openConnection() as HttpURLConnection
val inputStream = urlConnection.inputStream
// get text from stream, convert to string and send to main thread.
val allText = inputStream.bufferedReader().use { it.readText() }
content.append(allText)
val str = content.toString()
val msg = myHandler.obtainMessage()
msg.what = 0
msg.obj = str
myHandler.sendMessage(msg)
} catch (e: Exception) {
Log.d("Error", e.toString())
}
}
}
}
您可以使用 RequestQueue:https ://developer.android.com/training/volley/requestqueue
val textView = findViewById<TextView>(R.id.text)
// ...
// Instantiate the RequestQueue.
val queue = Volley.newRequestQueue(this)
val url = "https://www.google.com"
// Request a string response from the provided URL.
val stringRequest = StringRequest(Request.Method.GET, url,
Response.Listener<String> { response ->
// Display the first 500 characters of the response string.
textView.text = "Response is: ${response.substring(0, 500)}"
},
Response.ErrorListener { textView.text = "That didn't work!" })
// Add the request to the RequestQueue.
queue.add(stringRequest)