-->

How to read JSON from Url using kotlin Android?

2019-08-20 06:38发布

问题:

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?

回答1:

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



回答2:

Try this

fun parse(json: String): JSONObject? {
        var jsonObject: JSONObject? = null
        try {
            jsonObject = JSONObject(json)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        return jsonObject
    }


回答3:

You can use Volley or Retrofit library in Kotlin.Actually you can use all Java libraries in Kotlin.

Volley is more easier but Retrofit more faster than Volley.Your choice.

Volley Link

Retrofit Link



回答4:

Finally am getting answer from Here

Read Json data using Retrofit 2.0 RxJava, RxAndroid, Kotlin Android Extensions.

  fun provideRetrofit(): Retrofit {
    return Retrofit.Builder()
            .baseUrl("https://www.example.com")
            .addConverterFactory(MoshiConverterFactory.create())
            .build()
    }

Module

interface  Api {
@GET("/top.json")
fun getTop(@Query("after") after: String,
           @Query("limit") limit: String): Call<NewsResponse>;
}


回答5:

readText() is the approach Antonio Leiva uses when he introduces Networking in his book Kotlin for Android Developers (and also in the blog post as per dgrcode's answer) However I'm not sure if readText() is the right approach in general for requesting JSON responses from a URL as the response can be very large (Even Antonio mentions affirms the fact that Kotlin docs say there is a size limit to readText). According to this discussion, you should be using streams instead of readText. I would like to see a response to this answer using that approach or whatever is most concise and optimal in Kotlin, without adding library dependencies.

See also this thread

Note also that Antonio does offer alternatives in that blog post for situations when readText() is not the appropriate choice. I'd love to see someone provide some clarity on when it is appropriate or not though.