Skip to main content

Android: Using Gson in your Android Project

 

  • Gson is a Java library that can be used to convert Java Objects into their JSON representation.
  • Gson can be found on Github here: https://github.com/google/gson
  • Look for the Gson release you want to use. It will most likely be the most current release.
  • Add the dependency to app/build.gradle
    • Add Gson as a dependency to your MODULE LEVEL build.gradle configuration
    • dependencies {
           implementation 'com.google.code.gson:gson:2.8.6' 
      }

The configuration file will have other dependences so it will look more like this

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.code.gson:gson:2.8.6'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

}

Be sure to sync you new Gradle configuration. There is a button in the toolbar marked "Sync project with Gradle Files"

You will need to import Gson to use it in your app as shown below

package com.example.examplectivities

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.gson.Gson

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    val gson = Gson()

}