第一行代码 第三版 第11章网络技术 11.4 解析JSON格式数据 以及回调的实现

11.4 解析JSON格式数据

准备数据:
在这里插入图片描述

11.4.1 使用JSONObject

JSONObject这是官方提供的

由于在服务器中定义的是一个JSON数组。
将返回的数据传入一个JSONArray对象中;
循坏遍历JSONArray对象,从中取出的每一个元素都是一个JSONObject对象 ;
从JSONObject对象中取出相应的数据。

private fun parseJSONWithJSONObject(jsonData:String){
        try {
            val jsonArray = JSONArray(jsonData)  //将返回的数据传入一个JSONArray对象中
            for (i in 0 until jsonArray.length()){
                val jsonObject = jsonArray.getJSONObject(i)
                val id = jsonObject.getString("id")
                val name = jsonObject.getString("name")
                val version = jsonObject.getString("version")
                Log.d("MainActivity","id = $id")
                Log.d("MainActivity","name = $name")
                Log.d("MainActivity","version = $version")
            }
        }catch (e:Exception){
            e.printStackTrace()
        }
    }

14.4.2 使用GSON

GSON是Google 提供的开源库,用于解析JSON数据;附上该开源库的项目地址https://github.com/google/gson

要使用的话 ,需要添加GSON库的依赖。app/build.gradle 中的dependencies 闭包中添加。
在这里插入图片描述
GSON 库的强大之处在于可以将一段JSON格式的字符串自动映射成一个对象。
处理{"name":"Tom","age":20}这样的语句,需要创建一个类与之数据对应:

class XXX(val name:String ,val age:Int) {
}
//然后在需要的地方直接调用下面的代码
val gson =Gson()
 val x = gson.fromJson(jsonData,XXX::class.java)

针对JSON数组 还需要使用TypeToken 将期望解析成的数据类型传入fromJson() 方法中,

class App(val id :String,val name :String ,val version :String) {}//先建立与数据对应的类

private fun parseJSONWithGSON(jsonData: String){
	//下面的代码就是用处理JSON数组的方式
        val gson=Gson()
        val typeOf = object :TypeToken<List<App>>(){}.type
        val appList = gson.fromJson<List<App>>(jsonData,typeOf)
        for (app in appList){
            Log.d("MainActivity","id = ${app.id}")
            Log.d("MainActivity","name =${app.name}")
            Log.d("MainActivity","version = ${app.version}")
        }
    }

11.5 网络请求回调的实现方式

网络请求一般是耗时操作。
回调机制的使用:
在接口中定义一些方法,然后在对应的函数中传入该接口,最后在这个方法中调用接口参数的方法。

interface HttpCallbackListener {
    fun onFinish(response: String)//当服务器成功响应我们请求是调用
    fun onError(e:Exception)// 当网络操作出现错误的时候调用
}
//在HttpUtil 类中
fun sendHttpRequest(address: String ,listener: HttpCallbackListener){
        thread {
            var  connection :HttpURLConnection ?=null
            try{
                var response = StringBuilder()
                val url = URL(address)
                connection = url.openConnection() as HttpURLConnection
                connection.connectTimeout=8000
                connection.readTimeout = 8000
                val input =connection.inputStream
                val reader=BufferedReader(InputStreamReader(input))
                reader.use {
                    reader.forEachLine {
                        response.append(it)
                    }
                }
                //回调onFinish()方法
                listener.onFinish(response.toString())
            }catch (e:Exception){
                e.printStackTrace()
                //回调noError()方法
                listener.onError(e)
            }finally {
                connection?.disconnect()
            }
        }
    }

调用上面的方法

sendRequestBtn.setOnClickListener {
            //sendRequestWithOkHttp()
            HttpUtil.sendHttpRequest("http://10.0.2.2/get_data.json",
                object : HttpCallbackListener {
                    override fun onFinish(response: String) {
                        parseJSONWithGSON(response)
                    }

                    override fun onError(e: Exception) {

                    }
                })
        }

具体的写法可以参考第一行代码第三版P448。

发布了28 篇原创文章 · 获赞 11 · 访问量 2399

猜你喜欢

转载自blog.csdn.net/Y_an_Y/article/details/105778299