Mehedi Hassan Piash | Senior Software Engineer | Android | iOS | KMP | Ktor | Jetpack Compose | React-Native.

August 07, 2021

Read local json file from assets in android

August 07, 2021 Posted by Piash , No comments

 1. Extension to read JSON from assets 

 // Read json file from assets  
 fun AssetManager.readAssetsFile(fileName: String): String =  
   open(fileName).bufferedReader().use { it.readText() }  

 2. Use case of reading JSON 

  requireActivity().assets.readAssetsFile("country.json").fromPrettyJson<CountryName>()  

 3.  JSON to object and object to JSON extension 

 // Transform simple object to String with Gson  
 inline fun <reified T : Any> T.toPrettyJson() : String = Gson().toJson(this, T::class.java)  
 // Transform String Json to Object  
 inline fun <reified T : Any> String.fromPrettyJson() : T = Gson().fromJson(this , T::class.java)  
 // Transform String List Json to Object  
 inline fun <reified T : Any> String.fromPrettyJsonList() : MutableList <T> = when( this.isNotEmpty()){  
   true -> Gson().fromJson(this, object : TypeToken<MutableList<T>>() {}.type)  
   false -> mutableListOf()  
 }  

0 comments:

Post a Comment