-1

I'm trying to parse the following JSON File. It's on a different package and I'm trying to import it. I have tried installing different packages and adding dependencies on Gradle, but it seems unclear for me. Most of the tutorials have the folder assests where the json file is located or their version contains Java. Does anyone know how I can read the JSON file step by step with Kotlin on Android Studio?.

Shai Ishr
  • 21
  • 1
  • 3
  • Does this answer your question? [How to parse JSON in Kotlin?](https://stackoverflow.com/questions/41928803/how-to-parse-json-in-kotlin) – Ryan M Jan 26 '21 at 06:46

1 Answers1

1

I don't think you can do that directly from another module but there is a way with which you can do that, follow the steps below:

  1. Get JSON as a String from the Assets folder.

     fun readJSONFromAsset(): String? {
         var json: String? = null
         try {
             val  inputStream:InputStream = assets.open("yourFile.json")
             json = inputStream.bufferedReader().use{it.readText()}
         } catch (ex: Exception) {
             ex.printStackTrace()
             return null
         }
         return json
     }
    
  2. Parse that JSON with Gson.

     fun parseJSON() {
          Gson().fromJson(readJSONFromAsset(), YourObjectModel::class.java)
     }
    
  3. Make a class in the module in which JSON is present and place the above methods in it.

     class FetchJSONFromModule() {
    
        companion object {
    
           fun readJSONFromAsset(): String? {
               var json: String? = null
               try {
                   val  inputStream:InputStream = assets.open("yourFile.json")
                   json = inputStream.bufferedReader().use{it.readText()}
               } catch (ex: Exception) {
                   ex.printStackTrace()
                   return null
               }
               return json
           }
    
          fun parseJSON(): ObjectFromJson {
              return Gson().fromJson(readJSONFromAsset(), YourObjectModel::class.java)
          }
    
       }
    
     }
    
  4. Import the module ( in which JSON and above class is present) in the module in which you want to use the JSON by adding the dependency below;

implementation project(":YourModuleName")

  1. Then call the class, in the class in which you want to use the JSON

val data = FetchJSoNFromModule.parseJSON()