【Android开发】JSONObject解析

常用方法

  • getJSONObject(String name) 获取JSONObject对象
  • toString() 把JSONObject对象转换为json格式的字符串
class JSONActivity : AppCompatActivity() {
    
    
    private var txt1: TextView? = null
    private var txt2: TextView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_json)

        txt1 = findViewById(R.id.txt1)
        txt2 = findViewById(R.id.txt2)
        findViewById<View>(R.id.parse).setOnClickListener {
    
     parseByJSONObject() }
    }

    private fun parseByJSONObject() {
    
    
        object : Thread() {
    
    
            override fun run() {
    
    
                super.run()
                val s = get()
                //解析
                try {
    
    
                    //参数:满足json格式要求的字符串
                    val jo = JSONObject(s)
                    val status = jo.getInt("status")
                    val msg = jo.getString("msg")
                    Log.e("TAG", "$status$msg===")
                    val data = jo.getJSONObject("data")
                    val title = data.getString("title")

                    //显示到界面上
                    //此方法在子线程中调用,可以在内部处理界面的显示问题
                    //因为它相当于在此刻将操作权由子线程移交给了主线程
                    runOnUiThread {
    
    
                        txt1!!.text = msg
                        txt2!!.text = title
                    }
                } catch (e: JSONException) {
    
    
                    e.printStackTrace()
                }
            }
        }.start()
    }

    fun get(): String? {
    
    
        try {
    
    
            //HttpURLConnection
            //1.实例化一个URL对象
            val url = URL("http://www.imooc.com/api/teacher?type=3&cid=1&type=3")
            //2.获取HttpURLConnection实例
            val conn = url.openConnection() as HttpURLConnection
            //3.设置和请求相关的属性
            //请求方式
            conn.requestMethod = "GET"
            //请求超时时长
            conn.connectTimeout = 6000
            //4.获取响应码
            if (conn.responseCode == HttpURLConnection.HTTP_OK) {
    
    
                //5.判断响应码并获取响应数据
                //获取响应的流
                val inputStream = conn.inputStream
                val b = ByteArray(1024)
                var len = 0
                val baos = ByteArrayOutputStream()
                //在循环中读取输入的流
                //in.read(b); //该方法返回值是int类型数据,代表的是实际读到的数据长度
                while (inputStream.read(b).also {
    
     len = it } > -1) {
    
    
                    //将字节数组里面的内容存/写入缓存流
                    //参数1:待写入的数组
                    //参数2:起点
                    //参数3:长度
                    baos.write(b, 0, len)
                }
                val s = String(baos.toByteArray())
                Log.e("TAG", "$s====")
                return s
            }
        } catch (e: IOException) {
    
    
            e.printStackTrace()
        }
        return null
    }

}

解析JSONObject数组

class JSONActivity : AppCompatActivity() {
    
    
    private var txt1: TextView? = null
    private var txt2: TextView? = null
    private var listView: ListView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_json)
        txt1 = findViewById(R.id.txt1)
        txt2 = findViewById(R.id.txt2)
        listView = findViewById(R.id.list_view)
        findViewById<View>(R.id.parse).setOnClickListener {
    
     parseByJSONObject() }
    }

    private fun parseByJSONObject() {
    
    
        object : Thread() {
    
    
            override fun run() {
    
    
                super.run()
                val s = get()
                //解析
                try {
    
    
                    //参数:满足json格式要求的字符串
                    val jo = JSONObject(s)
                    val status = jo.getInt("status")
                    val msg = jo.getString("msg")
                    Log.e("TAG", "$status$msg===")

//                    JSONObject data = jo.getJSONObject("data");
//                    final String title = data.getString("title");
                    //为ListMap准备数据源
                    val list: MutableList<Map<String, String?>> = ArrayList()

                    //解析JSON数组
                    val array = jo.getJSONArray("data")
                    for (i in 0 until array.length()) {
    
    
                        //取出对应索引上的JSON对象
                        val obj = array.getJSONObject(i)
                        val name = obj.getString("name")
                        val id = obj.getString("id")
                        Log.e("TAG", "id=$id, name=$name")
                        val map: MutableMap<String, String?> = HashMap()
                        map["name"] = name
                        map["id"] = id
                        list.add(map)
                    }
                    val from = arrayOf("name", "id")
                    val to = intArrayOf(R.id.item_name, R.id.item_id)
                    //创建SimpleAdapter
                    val adapter =
                        SimpleAdapter(this@JSONActivity, list, R.layout.item, from, to)

                    //显示到界面上
                    //此方法在子线程中调用,可以在内部处理界面的显示问题
                    //因为它相当于在此刻将操作权由子线程移交给了主线程
                    runOnUiThread {
    
     listView!!.adapter = adapter }
                } catch (e: JSONException) {
    
    
                    e.printStackTrace()
                }
            }
        }.start()
    }

    fun get(): String? {
    
    
        try {
    
    
            //HttpURLConnection
            //1.实例化一个URL对象
            val url = URL("http://www.imooc.com/api/teacher?type=2&cid=1")
            //2.获取HttpURLConnection实例
            val conn = url.openConnection() as HttpURLConnection
            //3.设置和请求相关的属性
            //请求方式
            conn.requestMethod = "GET"
            //请求超时时长
            conn.connectTimeout = 6000
            //4.获取响应码
            if (conn.responseCode == HttpURLConnection.HTTP_OK) {
    
    
                //5.判断响应码并获取响应数据
                //获取响应的流
                val inputStream = conn.inputStream
                val b = ByteArray(1024)
                var len = 0
                val baos = ByteArrayOutputStream()
                //在循环中读取输入的流
                //in.read(b); //该方法返回值是int类型数据,代表的是实际读到的数据长度
                while (inputStream.read(b).also {
    
     len = it } > -1) {
    
    
                    //将字节数组里面的内容存/写入缓存流
                    //参数1:待写入的数组
                    //参数2:起点
                    //参数3:长度
                    baos.write(b, 0, len)
                }
                val s = String(baos.toByteArray())
                Log.e("TAG", "$s====")
                return s
            }
        } catch (e: IOException) {
    
    
            e.printStackTrace()
        }
        return null
    }

猜你喜欢

转载自blog.csdn.net/weixin_42020386/article/details/113093039