java android json数据读取

利用java原生方法提取

package com.example.apps.photogallery

import android.net.Uri
import android.util.Log
import com.google.gson.Gson
import org.json.JSONObject
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.nio.charset.Charset

class FlickrFetchr {
    private val TAG = "FlickrFetchr"
    /**
     * 获取数据
     */
    fun getUrlBytes(urlSpec: String): ByteArray {
        var url = URL(urlSpec) // 获取URL对象
        var connection: HttpURLConnection = url.openConnection() as HttpURLConnection // 打开连接
        try {
            var out = ByteArrayOutputStream() //
            var input = connection.inputStream// 真正连接到url地址,如果是post请求就用outputStream()方法
            if (connection.responseCode != HttpURLConnection.HTTP_OK) {
                throw IOException(connection.responseMessage + ": with" + urlSpec)
            }

            var buffer = ByteArray(1024)
            input.read(buffer).apply {
                out.write(buffer, 0, this) // 读取数据
            }

            out.close()
            return out.toByteArray()
        } finally {
            connection.disconnect()
        }
    }

    /**
     * 将获取的字节码转换为字符串
     */
    fun getUrlString(urlSpec: String): String {
        return String(getUrlBytes(urlSpec), Charset.forName("Utf-8"))
    }

    /**
     * 获取
     */
    public fun fetchItems(): MutableList<GalleryItem> {
        var items: MutableList<GalleryItem> = ArrayList<GalleryItem>()
        try {
            var baseUrl = "http://www.qiyu.site:8888/api"
            var url = Uri.parse(baseUrl)
                .buildUpon()
//                .appendQueryParameter("type", "1")
                .appendQueryParameter("return", "json")
                .build().toString() // 构建请求url
            var jsonString = getUrlString(url)
            //var jsonBody = JSONObject(jsonString)
            var jsonBody = Gson().fromJson(jsonString, JSONObject::class.java)
            var photoJsonArray = jsonBody.getJSONArray("photo")
            for (i in 0 until photoJsonArray.length()) {
                var photo = photoJsonArray[i] as JSONObject
                var item = GalleryItem()
                item.mId = photo.getString("id");
                item.mCaption = photo.getString("title");
                if (photo.has("imgurl")) {
                    item.mUrl = photo.getString("imgurl")
                    items.add(item)
                }
            }

            return items
        } catch (ioe: IOException) {
            Log.e(TAG, "Failed to fetch items", ioe)
        }
        return items
    }
}

使用GSON

// 在 kotlin中扩展 Java 类的 Gson.fromJson 方法
// 不在传入 T 的class,inline 的作用就是将函数插入到被调用处,配合 reified 就可以获取到 T 真正的类型
inline fun <reified T : Any> Gson.fromJson(json: String): T {
    return Gson().fromJson(json, T::class.java)
}
// main 方法
fun main(args: Array<String>) {
    var json = File("singer.json").readText()
    var single: Singer = Gson().fromJson(json)
    println(single)
}
// 打印信息
Singer(id=12, name=UnKnown)

具体使用

package com.example.apps.photogallery

import android.net.Uri
import android.util.Log
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.json.JSONObject
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
import java.nio.charset.Charset

class FlickrFetchr {
    private val TAG = "FlickrFetchr"
    /**
     * 获取数据
     */
    fun getUrlBytes(urlSpec: String): ByteArray {
        var url = URL(urlSpec) // 获取URL对象
        var connection: HttpURLConnection = url.openConnection() as HttpURLConnection // 打开连接
        try {
            var out = ByteArrayOutputStream() //
            var input = connection.inputStream// 真正连接到url地址,如果是post请求就用outputStream()方法
            if (connection.responseCode != HttpURLConnection.HTTP_OK) {
                throw IOException(connection.responseMessage + ": with" + urlSpec)
            }

            var buffer = ByteArray(1024)
            input.read(buffer).apply {
                out.write(buffer, 0, this) // 读取数据
            }
            out.flush()
            out.close()
            return out.toByteArray()
        } finally {
            connection.disconnect()
        }
    }

    /**
     * 将获取的字节码转换为字符串
     */
    fun getUrlString(urlSpec: String): String {
        return String(getUrlBytes(urlSpec), Charset.forName("Utf-8"))
    }

    inline fun <reified T : Any> Gson.fromJson(json: String): T {
        return Gson().fromJson(json, T::class.java)
    }

    /**
     * 获取
     */

    fun fetchItems(): MutableList<GalleryItem> {
        var items: MutableList<GalleryItem> = ArrayList<GalleryItem>()
        try {
            var baseUrl = "http://www.qiyu.site:8888/api"
            var url = Uri.parse(baseUrl)
                .buildUpon()
//                .appendQueryParameter("type", "1")
                .appendQueryParameter("return", "json")
                .build().toString() // 构建请求url
            var jsonString = getUrlString(url)
            //var jsonBody = JSONObject(jsonString)
            var jsonBody: ResponseEntity<Map<*, *>> =
                Gson().fromJson(jsonString)
            var photoJsonArray = jsonBody.mData?.get("photo") as ArrayList<*>
            for (i in 0 until photoJsonArray.size) {
                var photo = photoJsonArray[i] as Map<*, *>
                var item = GalleryItem()
                item.mId = photo.get("id").toString();
                item.mCaption = photo.get("title") as String;
                if (photo.containsKey("imgurl")) {
                    var url = photo.get("imgurl")
                    item.mUrl = url as String
                    items.add(item)
                }
            }

            return items


        } catch (e: Exception) {
            Log.e(TAG, "Failed to fetch items", e)
        }
        return items
    }
}
发布了76 篇原创文章 · 获赞 1 · 访问量 9382

猜你喜欢

转载自blog.csdn.net/qq_40414209/article/details/105081497