How to convert a JSON into usable data in Kotlin
A step by step tutorial on converting a JSON into usable data in Android Studio using Kotlin.
Step One: Create the JSON
Create a json file using the tutorial linked below.
Step Two: Create the Data Class File
In the models folder, create a new file named after the class that you wish to associate with your json.
In our case, we have called it UIContent.kt, as we will use it to read a language JSON that will be used to populate UI strings.
Step Three: Create JSON Data Class
In the file created in Step Two, create a data class that matches the JSON you wish to convert into usable data.
We have provided a sample of how to do this below.
Step Four: Create the convert JSON to string functionality
Follow the tutorial below to implement the functionality required to read the JSON and convert it to a string.
Step Five: Add Gson to project
In order to convert the JSON string into usable data, we need to use the Gson library.
Navigate to your app level build gradle (i.e. build.gradle.kt (Module :app)) and add the following line to the dependencies:
implementation("com.google.code.gson:gson:2.8.9")
Please note that version 2.8.9 was the latest version available when we wrote this tutorial but may not be the latest version available when you implement this. Please update this string to use the latest version available.
Step Six: Sync the Gradle Files
Sync the Gradle files to make sure the Gson library registers.
Step Seven: Convert the JSON String to Data
To convert the JSON string gathered from the function created in Step Four into the data class created in Step Three, use code similar to the one below:
val data = Gson().fromJson(jsonString, UIContent::class.java)
Step Eight: Implement Data
To use the data, use dot notation with parameters that match the class that you created in Step Three (i.e. data.sample.sampleString or data.sampleTwo.sampleB.aSampleString).
Step Nine: Test
Run the app on a device and confirm that the JSON is read and the data is processed.
Verification can be done by printing to a Log or printing to the screen, as we have done in this tutorial.
Looking to learn how to make an Android localization manager ?
To learn our design system for localizing apps into multiple languages, follow the tutorial below.
Warning: Data classes cannot be obfuscated
To guarantee that the app functions as expected on release, you should add ANY JSON data classes to the projects proguard-rules.pro file.