Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
114 views
in Technique[技术] by (71.8m points)

How to parse a JSON file in Kotlin on Android Studio

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?.

question from:https://stackoverflow.com/questions/65875130/how-to-parse-a-json-file-in-kotlin-on-android-studio

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...