package com.cheng.blzb.utils

import android.content.Context
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader


object JsonUtils {

    fun loadJsonArrayFromAsset(context: Context, fileName: String): JSONArray? {
        var jsonArray: JSONArray? = null
        try {
            //获取本地的Json文件
            val open: InputStream = context.assets.open(fileName)
            val isr = InputStreamReader(open, "UTF-8")
            val br = BufferedReader(isr)
            var line: String?
            val builder = StringBuilder()
            while (br.readLine().also { line = it } != null) {
                builder.append(line)
            }
            br.close()
            isr.close()
            jsonArray = JSONArray(builder.toString())
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        return jsonArray
    }

    fun loadJsonFromAsset(context: Context, fileName: String): JSONObject? {
        var jsonObject: JSONObject? = null
        try {
            //获取本地的Json文件
            val open: InputStream = context.assets.open(fileName)
            val isr = InputStreamReader(open, "UTF-8")
            val br = BufferedReader(isr)
            var line: String?
            val builder = StringBuilder()
            while (br.readLine().also { line = it } != null) {
                builder.append(line)
            }
            br.close()
            isr.close()
            jsonObject = JSONObject(builder.toString())
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        return jsonObject
    }
}