How to read JSON from Url using kotlin Android?

痴心易碎 提交于 2020-01-15 01:52:26

问题


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:


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>;
}



回答4:


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.




回答5:


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




回答6:


I have a fragment_X (class + layout) where i would like to read the online Json file, (you also able to read txt file), and show the content to TextView.

==> NOTE: give application have a right to access internet in 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())
            }
        }

    }

}


来源:https://stackoverflow.com/questions/44883593/how-to-read-json-from-url-using-kotlin-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!