从文件中读取内容转成json字符串
//从文件中读取内容转成json字符串
private fun file2JsonStr(fileName: String): String? {
val stringBuilder = StringBuilder()
try {
val assetManager: AssetManager = getApplication<Application>().assets
val isr = InputStreamReader(assetManager.open(fileName))
val bf = BufferedReader(isr)
var line: String?
while (bf.readLine().also { line = it } != null) {
stringBuilder.append(line)
}
bf.close()
isr.close()
return stringBuilder.toString()
} catch (e: IOException) {
e.printStackTrace()
}
return null
}
json字符串转列表
//json字符串转列表
private fun jsonStr2List(jsonStr: String?): ArrayList<JsonBean> {
val list = ArrayList<JsonBean>()
val data = JSONArray(jsonStr)
val gson = Gson()
for (i in 0 until data.length()) {
val entity: JsonBean =
gson.fromJson(data.optJSONObject(i).toString(), JsonBean::class.java)
list.add(entity)
}
return list
}
引用方法示例如下:
//xxxx.json是文件名,通常放在assesst文件夹下面
val jsonStr = file2JsonStr("xxxx.json")
val dataList = jsonStr2List(jsonStr)
获取到了dataList 信息之后,就可以使用dataList .xxx获取你需要的数据了
json文件放置位置