📅  最后修改于: 2021-01-05 08:35:48             🧑  作者: Mango
JSON是指JavaScript对象符号,它是一种编程语言。 JSON用于解析服务器和客户端之间的数据。它是最少的,文本的并且是JavaScript的子集。它是XML解析的替代方法。
JSON对象包含键/值对,如地图。键是字符串,值是JSON类型。逗号分隔键和值(,)。花括号{}表示JSON对象。
在此示例中,我们从URL解析JSON数据并将其绑定到ListView中。 JSON数据包含“ id”,“ name”,“ email”。
创建一个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)时,如下所示:
在activity_main.xml布局文件中添加ListView。
在build.gradle文件中添加以下okhttp依赖项。
compile 'com.squareup.okhttp3:okhttp:3.8.1'
创建一个数据模型类Model.kt,其中包含信息字符串“ id”,字符串“ name”和字符串“ email”。
package example.javatpoint.com.kotlinjsonparsing
public class Model{
lateinit var id:String
lateinit var name:String
lateinit var email:String
constructor(id: String,name:String,email:String) {
this.id = id
this.name = name
this.email = email
}
constructor()
}
在布局目录中创建一个adapter_layout.xml文件,其中包含ListView的行项目。
创建一个自定义适配器类CustomAdapter.kt并扩展BaseAdapter来处理自定义ListView。
package example.javatpoint.com.kotlinjsonparsing
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.LinearLayout
import android.widget.TextView
class CustomAdapter(context: Context,arrayListDetails:ArrayList) : BaseAdapter(){
private val layoutInflater: LayoutInflater
private val arrayListDetails:ArrayList
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: ListRowHolder
if (convertView == null) {
view = this.layoutInflater.inflate(R.layout.adapter_layout, parent, false)
listRowHolder = ListRowHolder(view)
view.tag = listRowHolder
} else {
view = convertView
listRowHolder = view.tag as ListRowHolder
}
listRowHolder.tvName.text = arrayListDetails.get(position).name
listRowHolder.tvEmail.text = arrayListDetails.get(position).email
listRowHolder.tvId.text = arrayListDetails.get(position).id
return view
}
}
private class ListRowHolder(row: View?) {
public val tvName: TextView
public val tvEmail: TextView
public val tvId: TextView
public val linearLayout: LinearLayout
init {
this.tvId = row?.findViewById(R.id.tvId) as TextView
this.tvName = row?.findViewById(R.id.tvName) as TextView
this.tvEmail = row?.findViewById(R.id.tvEmail) as TextView
this.linearLayout = row?.findViewById(R.id.linearLayout) as LinearLayout
}
}
在MainActivity.kt类文件中添加以下代码。此类读取JSON对象形式的JSON数据。使用JSON对象,我们读取JSON数组数据。 JSON数据绑定在ArrayList中。
package example.javatpoint.com.kotlinjsonparsing
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.ListView
import android.widget.ProgressBar
import okhttp3.*
import org.json.JSONArray
import org.json.JSONObject
import java.io.IOException
import kotlin.collections.ArrayList
class MainActivity : AppCompatActivity() {
lateinit var progress:ProgressBar
lateinit var listView_details: ListView
var arrayList_details:ArrayList = ArrayList();
//OkHttpClient creates connection pool between client and server
val client = OkHttpClient()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
progress = findViewById(R.id.progressBar)
progress.visibility = View.VISIBLE
listView_details = findViewById(R.id.listView) as ListView
run("http://10.0.0.7:8080/jsondata/index.html")
}
fun run(url: String) {
progress.visibility = View.VISIBLE
val 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 object
val json_contact:JSONObject = JSONObject(str_response)
//creating json array
var jsonarray_info:JSONArray= json_contact.getJSONArray("info")
var i:Int = 0
var 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 ui
val obj_adapter : CustomAdapter
obj_adapter = CustomAdapter(applicationContext,arrayList_details)
listView_details.adapter=obj_adapter
}
progress.visibility = View.GONE
}
})
}
}
在AndroidManifest.xml文件中添加Internet权限。
输出: