使用URL的Kotlin Android JSON解析

【使用URL的Kotlin Android JSON解析】JSON是指JavaScript对象表示法, 它是一种编程语言。 JSON用于解析服务器和客户端之间的数据。它是最少的, 文本的并且是JavaScript的子集。它是XML解析的替代方法。
JSON优于XML的优势

  1. 对于AJAX应用程序, JSON比XML更快, 更容易。
  2. 与XML不同, 它更短, 更快地读取和写入。
  3. 它使用一个数组。
JSON对象
JSON对象包含键/值对, 如地图。键是字符串, 值是JSON类型。逗号分隔键和值(, )。花括号{}表示JSON对象。
使用网址示例的Kotlin JSON解析 在此示例中, 我们从URL解析JSON数据并将其绑定到ListView中。 JSON数据包含“ id”, “ name”, “ email”。
JSON数据index.html
创建一个JSON文件index.html。
{"info":[{"name":"Ajay", "id":"111", "email":"ajay@gmail.com"}, {"name":"John", "id":"112", "email":"john@gmail.com"}, {"name":"Rahul", "id":"113", "email":"rahul@gmail.com"}, {"name":"Maich", "id":"114", "email":"maich@gmail.com"}, {"name":"Vikash", "id":"115", "email":"vikash@gmail.com"}, {"name":"Mayank", "id":"116", "email":"mayank@gmail.com"}, {"name":"Prem", "id":"117", "email":"prem@gmail.com"}, {"name":"Chandan", "id":"118", "email":"chandan@gmail.com"}, {"name":"Soham", "id":"119", "email":"soham@gmail.com"}, {"name":"Mukesh", "id":"120", "email":"mukesh@gmail.com"}, {"name":"Ajad", "id":"121", "email":"ajad@gmail.com"}]}

执行JSON文件(index.html)时, 如下所示:
使用URL的Kotlin Android JSON解析

文章图片
activity_main.xml
在activity_main.xml布局文件中添加ListView。
< ?xml version="1.0" encoding="utf-8"?> < android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="example.srcmini.com.kotlinjsonparsing.MainActivity"> < ListViewandroid:id="@+id/listView"android:layout_width="match_parent"android:layout_height="match_parent"> < /ListView> < /android.support.constraint.ConstraintLayout>

build.gradle
在build.gradle文件中添加以下okhttp依赖项。
compile 'com.squareup.okhttp3:okhttp:3.8.1'

Model.kt
创建一个数据模型类Model.kt, 其中包含信息字符串“ id”, 字符串“ name”和字符串“ email”。
package example.srcmini.com.kotlinjsonparsingpublic class Model{lateinit var id:Stringlateinit var name:Stringlateinit var email:Stringconstructor(id: String, name:String, email:String) {this.id = idthis.name = namethis.email = email}constructor()}

adapter_layout.xml
在布局目录中创建一个adapter_layout.xml文件, 其中包含ListView的行项目。
< ?xml version="1.0" encoding="utf-8"?> < LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/linearLayout"android:padding="5dp"android:orientation="vertical"> < TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/tvId"android:layout_margin="5dp"android:textSize="16dp"/> < TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/tvName"android:textSize="16dp"android:layout_margin="5dp"/> < TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/tvEmail"android:layout_margin="5dp"android:textSize="16dp"/> < /LinearLayout>

CustomAdapter.kt
创建一个自定义适配器类CustomAdapter.kt并扩展BaseAdapter来处理自定义ListView。
package example.srcmini.com.kotlinjsonparsingimport android.content.Contextimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.BaseAdapterimport android.widget.LinearLayoutimport android.widget.TextViewclass CustomAdapter(context: Context, arrayListDetails:ArrayList< Model> ) : BaseAdapter(){private val layoutInflater: LayoutInflaterprivate val arrayListDetails:ArrayList< Model> init {this.layoutInflater = LayoutInflater.from(context)this.arrayListDetails=arrayListDetails}override fun getCount(): Int {return arrayListDetails.size}override fun getItem(position: Int): Any {return arrayListDetails.get(position)}override fun getItemId(position: Int): Long {return position.toLong()}override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {val view: View?val listRowHolder: ListRowHolderif (convertView == null) {view = this.layoutInflater.inflate(R.layout.adapter_layout, parent, false)listRowHolder = ListRowHolder(view)view.tag = listRowHolder} else {view = convertViewlistRowHolder = view.tag as ListRowHolder}listRowHolder.tvName.text = arrayListDetails.get(position).namelistRowHolder.tvEmail.text = arrayListDetails.get(position).emaillistRowHolder.tvId.text = arrayListDetails.get(position).idreturn view}}private class ListRowHolder(row: View?) {public val tvName: TextViewpublic val tvEmail: TextViewpublic val tvId: TextViewpublic val linearLayout: LinearLayoutinit {this.tvId = row?.findViewById< TextView> (R.id.tvId) as TextViewthis.tvName = row?.findViewById< TextView> (R.id.tvName) as TextViewthis.tvEmail = row?.findViewById< TextView> (R.id.tvEmail) as TextViewthis.linearLayout = row?.findViewById< LinearLayout> (R.id.linearLayout) as LinearLayout}}

MainActivity.kt
在MainActivity.kt类文件中添加以下代码。此类读取JSON对象形式的JSON数据。使用JSON对象, 我们读取JSON数组数据。 JSON数据绑定在ArrayList中。
package example.srcmini.com.kotlinjsonparsingimport android.support.v7.app.AppCompatActivityimport android.os.Bundleimport android.view.Viewimport android.widget.ListViewimport android.widget.ProgressBarimport okhttp3.*import org.json.JSONArrayimport org.json.JSONObjectimport java.io.IOExceptionimport kotlin.collections.ArrayListclass MainActivity : AppCompatActivity() {lateinit var progress:ProgressBarlateinit var listView_details: ListViewvar arrayList_details:ArrayList< Model> = ArrayList(); //OkHttpClient creates connection pool between client and serverval client = OkHttpClient()override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)progress = findViewById(R.id.progressBar)progress.visibility = View.VISIBLElistView_details = findViewById< ListView> (R.id.listView) as ListViewrun("http://10.0.0.7:8080/jsondata/index.html")}fun run(url: String) {progress.visibility = View.VISIBLEval request = Request.Builder().url(url).build()client.newCall(request).enqueue(object : Callback {override fun onFailure(call: Call, e: IOException) {progress.visibility = View.GONE}override fun onResponse(call: Call, response: Response) {var str_response = response.body()!!.string()//creating json objectval json_contact:JSONObject = JSONObject(str_response)//creating json arrayvar jsonarray_info:JSONArray= json_contact.getJSONArray("info")var i:Int = 0var size:Int = jsonarray_info.length()arrayList_details= ArrayList(); for (i in 0.. size-1) {var json_objectdetail:JSONObject=jsonarray_info.getJSONObject(i)var model:Model= Model(); model.id=json_objectdetail.getString("id")model.name=json_objectdetail.getString("name")model.email=json_objectdetail.getString("email")arrayList_details.add(model)}runOnUiThread {//stuff that updates uival obj_adapter : CustomAdapterobj_adapter = CustomAdapter(applicationContext, arrayList_details)listView_details.adapter=obj_adapter}progress.visibility = View.GONE}})}}

AndroidManifest.xml
在AndroidManifest.xml文件中添加Internet权限。
< uses-permission android:name="android.permission.INTERNET"/>

输出:
使用URL的Kotlin Android JSON解析

文章图片

    推荐阅读