I have already done with java but find difficult with Kotlin.
I have already search with google but none of them work for me.
/**
* Get the json data from json file.
*
* @param context the context to acces the resources.
* @param fileName the name of the json file
* @return json as string
*/
public static String getJsonFromAsset(Context context, String fileName) {
String json = "";
try {
InputStream stream = context.getAssets().open(fileName);
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
json = new String(buffer, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
I want this code in Kotlin.
Java codes can be converted to Kotlin from Android Studio too. Here is the converted solution with the extension function of Context .
@Throws(IOException::class)
fun Context.readJsonAsset(fileName: String): String {
val inputStream = assets.open(fileName)
val size = inputStream.available()
val buffer = ByteArray(size)
inputStream.read(buffer)
inputStream.close()
return String(buffer, Charsets.UTF_8)
}
Reading json file from assets folder in Kotlin is very easy, just use the following code
val fileInString: String =
applicationContext.assets.open(fileName).bufferedReader().use { it.readText() }
You can use the following
class LocalJSONParser {
companion object {
fun inputStreamToString(inputStream: InputStream): String {
try {
val bytes = ByteArray(inputStream.available())
inputStream.read(bytes, 0, bytes.size)
return String(bytes)
} catch (e: IOException) {
return ""
}
}
}
}
// jsonFileName = "data.json"
inline fun <reified T> Context.getObjectFromJson(jsonFileName: String): T {
val myJson =LocalJSONParser.inputStreamToString(this.assets.open(jsonFileName))
return Gson().fromJson(myJson, T::class.java
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.